【发布时间】:2020-12-10 15:58:59
【问题描述】:
我被告知您必须使用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
}
}
【问题讨论】:
-
您是否尝试过由 firstname 和 lastname 组成的名字?例如“彼得鱼”?
-
不要使用
gets,这是一个不推荐使用的函数,并且有充分的理由:"在给定足够长的输入字符串的情况下,该函数无法防止目标数组的缓冲区溢出。std ::gets 在 C++11 中已弃用,并从 C++14 中删除。可以使用 std::fgets 代替。"