我曾经学过,输入字符串必须使用
以下是代码:
gets(str)
而不是cin
。然而,在下面的程序中我可以成功地使用cin
。请问是否可以使用cin
?抱歉我的英语不好。该程序允许您插入5个名称,然后将这些名称打印到屏幕上。以下是代码:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char **p = new char *[5];
for (int i = 0; i < 5; i++)
{
*(p + i) = new char[255];
} //make a 2 dimensional array of strings
for (int i = 0; i < n; i++)
{
char n[255] = "";
cout << "insert names: ";
cin >> n; //how i can use cin here to insert the string to an array??
strcpy(p[i], n);
}
for (int i = 0; i < n; i++)
{
cout << p[i] << endl; //print the names
}
}
gets
,它是一个已弃用的函数,而且有充分的理由:"该函数无法防止目标数组的缓冲区溢出,即使输入字符串足够长。在C++11中,std::gets被弃用,并在C++14中被移除。可以使用std::fgets代替。" - anastaciu