如何在C中获得一组带有空格的单词作为一个输入

How to get a set of words with spaces as one input in C?

本文关键字:空格 单词作 输入 一个 一组      更新时间:2023-10-16

在我创建的程序中,我需要将一些客户信息获取到一个数组中。以下是关于我的问题的代码。

struct CustomerType
{
    string fName;
    string lName;
    char gender;
    string address;
    string contactNo;
};
CustomerType Customer[1000];

我有下面的代码从用户获取输入。这里i是我正在获取信息的客户的索引。

string add="";
cout<<left<<"n"<<setw(29)<<"tt Name"<<": ";
    cin>>Customer[i].fName>>Customer[i].lName;
cout<<left<<"n"<<setw(29)<<"tt Gender"<<": ";
    cin>>Customer[i].gender;
cout<<left<<"n"<<setw(29)<<"tt Address"<<": ";
    getline(cin,add); Customer[i].address=add;
cout<<left<<"n"<<setw(29)<<"tt Contact No."<<": ";
    cin>>Customer[i].contactNo;

但是当我运行程序时,它只要求输入姓名,性别和联系电话。但没有地址。它的工作原理就像没有getline命令。

如何解决这个问题?

这是旧的问题,如果" getline不跳过换行输入,但operator >>做"的问题。简单的解决方案包括:

  1. 使用cin.ignore(1000, 'n');跳过下一个换行符(假设换行符前少于1000个字符)。这一行在getline调用之前。
  2. 一般只使用getline读取数据,然后使用其他方法读取实际内容。[在你的情况下,唯一有点困难的是gender成员变量-但你可能想处理某人写"女性",然后地址在某种程度上变成"女性",所以可能不是一个大问题。

如果在cin之后使用getline,则需要在使用cin后刷新缓冲区。如果您不这样做,getline命令将尝试读取缓冲区并获取cin剩余的"endline",并将其自动用作其输入。

只需将cin.ignore();放在getline();或者像在c中那样使用fflush(stdin)。