【问题标题】:How to get a set of words with spaces as one input in C?如何获得一组带有空格的单词作为C中的一个输入?
【发布时间】:2013-05-18 17:40:54
【问题描述】:

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

struct CustomerType
{
    string fName;
    string lName;
    char gender;
    string address;
    string contactNo;
};

CustomerType Customer[1000];

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

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

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

我该如何解决这个问题?

【问题讨论】:

  • 如果您在运算符周围使用空格,您的代码会更容易阅读。顺便说一句,不使用空格的编译过程中节省的时间可以忽略不计。
  • 我建议您在结构中添加功能以读取其成员。你的代码看起来像cin &gt;&gt; Customer[i];

标签: c++ visual-studio-2010 getline cin


【解决方案1】:

如果“getline 没有在输入中跳过换行符,但operator &gt;&gt; 可以”,这就是老问题了。简单的解决方案包括:

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

【讨论】:

  • 感谢您帮助我。我应该将cin.ignore(1000, '\n'); 放在代码中的什么位置?
  • cin &gt;&gt; std::ws; 呢?
  • @DishonMichael 编辑解释它的去向(在 getline 之前,&gt;&gt; 输入之后)
【解决方案2】:

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

您只需将 cin.ignore(); 放在 getline(); 之前即可做到这一点 或者像在 C 中那样使用 fflush(stdin)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2019-01-11
    • 2017-03-24
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多