“ cin”怎么会陷入困境?

问题描述

我编写了一个程序,可以让您插入 n 名称,然后在屏幕上打印这些名称。当我将 n 设置为固定值时,程序运行正常。但是,当我添加cin命令cin>>n时,该程序似乎跳过了第一个循环。我注意到,每当我使用cin时都会出现问题。我想当我在cin命令中按Enter键时,告诉第一个循环是 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 >> n;

将读取您输入的所有数字,但随后的换行字符。然后,您通过调用gets()来拾取该换行符。最终导致名字为空。

您可以:

  • 在终端提示符下使用 Ctrl + D 代替 Return 来发送值而不发送换行符
  • 或者使用cin >> n >> ws跳过空白。在这种情况下,您还必须#include <iomanip>

此外,最好不要混用iostream和stdio函数,而应使用std::string而不是C字符串。