如何在C中获得一组带有空格的单词作为一个输入
How to get a set of words with spaces as one input in C?
在我创建的程序中,我需要将一些客户信息获取到一个数组中。以下是关于我的问题的代码。
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 >>
做"的问题。简单的解决方案包括:
- 使用
cin.ignore(1000, 'n');
跳过下一个换行符(假设换行符前少于1000个字符)。这一行在getline
调用之前。 - 一般只使用
getline
读取数据,然后使用其他方法读取实际内容。[在你的情况下,唯一有点困难的是gender
成员变量-但你可能想处理某人写"女性",然后地址在某种程度上变成"女性",所以可能不是一个大问题。
如果在cin之后使用getline,则需要在使用cin后刷新缓冲区。如果您不这样做,getline命令将尝试读取缓冲区并获取cin剩余的"endline",并将其自动用作其输入。
只需将cin.ignore();放在getline();或者像在c中那样使用fflush(stdin)。
相关文章:
- C++为一串单词添加空格
- 在单词之间添加空格
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 单词exp和带空格的字符串
- 单词之间的莫尔斯电码空格问题
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- 如何用C 中的文件中忽略空格读单词
- C++ 在空格不规则的字符串中迭代单词
- 如何在两个单词之间添加空格
- 在字符串中找到单词出现数量的最佳方法(C ,字符串中没有空格)
- 如何将空格读作C++中的字符
- 删除 C++ 中字符串中第一个单词之前的空格
- 匹配由符号分隔的重复单词,忽略空格
- 如何使用C 中的Regex在给定句子中的多个空格隔开的两个单词匹配
- C++均匀地分配单词之间的空格
- 增加单词之间的空格,按列排列单词
- 从字符串中读取单词C++,同时忽略空格、数字和符号
- 如何按空格循环字符串?我怎么知道字符串中我当前所在的单词的索引号
- 增强字符串拆分以消除单词中的空格
- 确定单词后跟的是空格还是换行符