【发布时间】:2020-08-21 12:46:06
【问题描述】:
我编写了一个程序,可以让您插入 n 个名称,然后在屏幕上打印这些名称。当我将 n 设置为固定值时,程序运行良好。但是,当我添加 cin 命令 cin>>n 时,程序似乎跳过了第一个循环。我注意到每当我使用cin 时,都会出现问题。我想当我在输入的cin命令上按回车时,告诉第一个循环
n[0]=''(也许)。你们能帮我解决这个问题吗?对不起我的英语。
代码如下:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{int n;cin>>n;//the root of the problem(i think)
char **p = new char *[n];
for (int i = 0; i < n; 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 no."<<i+1<<": ";
gets(n);
strcpy(p[i], n);//insert the names into the array of strings
}
for (int i = 0; i < n; i++)
{
cout << p[i] << endl; //print the names
}
}
【问题讨论】:
-
使用
cin读取 int 不会消耗您发送的换行符,因此下一次读取会消耗它 -
您应该检查 cin 后面的
n的值,以验证它是一个有效值。还要检查 cin >> n 是否成功, -
我可以原谅你的英语,但你的 C++ 需要改进 ;)
-
gets - “C 标准的最新版本 (2011) 已明确从其规范中删除了此函数。该函数在 C++ 中已弃用(截至 2011 年标准,如下C99+TC3)。”
-
char n为什么要重复使用n?