为什么在"cin"后使用 "getline" 时需要 cin.ignore(),而多次使用 "cin" 时不需要?
Why is cin.ignore() necessary when using "getline" after "cin", but is not required when using "cin" multiple times?
在我所知,当cin
之后使用getline()
时,我们需要先在调用getline()
之前先冲洗缓冲区中的newline字符,然后通过调用cin.ignore()
。
std::string name, address;
std::cin >> name;
std::cin.ignore(); //flush newline character
getline(std::cin,address);
但是,当使用多个cin
时,我们不需要冲洗Newline字符。
std::string firstname, lastname;
std::cin >> firstname;
std::cout << firstname << std::endl;
//no need to flush newline character
std::cin >> lastname;
std::cout << lastname << std::endl;
为什么?为什么在第一种情况下需要cin.ignore()
,而不是最后一个?
,因为 getline()
读取,直到给定std::istream
的下一个newline targue the newline the std::istream::operator>>()
skips> skips 任何whitespaces> newlines )。
因此,当您读取整数或浮点数时,所有尾随的空格都留在输入流中。当您从控制台或终端阅读时,您将键入数据并击中输入,后者将留在流中,如果您不清除它,将被getline()
捕获。
您不必清除它,因为下次阅读std::string
时,std::istream::operator>>()
会为您跳过Whitespaces。
考虑此代码段;
std::string a, b;
std::cin >> a;
std::getline(std::cin, b);
和此输入:
Stack Overflow<Enter>
Where developers learn.<Enter>
第一个cin
语句将读取Stack
一词,并留下一个空间,而Overflow<Enter>
则落后。然后,它将由getline
读取,所以
assert(b == " Overflow");
如果您在调用getline()
之前插入std::cin.ignore()
,则它将变成
assert(b == "Where developers learn.");
signed main(){
/*
* input is of next two lines
* Stack Overflow<Enter>
* Where developers learn.<Enter>
* for more about cin.ignore visit http://www.cplusplus.com/reference/istream/istream/ignore/
*/
string name, address;
cin>>name;
//cin.ignore();
//cin.ignore(256,'n');
getline(cin,address);
cout << address << endl;
assert(address == " Overflow"); // breaks if using cin.ignore() or cin.ignore(256,'n')
assert(address == "Overflow"); // breaks if using cin.ignore(256,'n') OR not using any
assert(address == "Where developers learn."); // breaks if using cin.ignore() or not using ignore
}
输入输入
堆栈溢出
开发人员学习的地方。
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 为什么output_editor Concept不需要output_e迭代器标记
- 在除法中不需要四舍五入
- 与C代码相比,为什么C++代码不需要"#define _POSIX_C_SOURCE 200809L"?
- 将值从另一个数组写入数组,不包括不需要的值 C++
- C++ 写入路径名中包含不需要的空字符的文件
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 使用 assimp 加载模型 - 不需要提升?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 返回不需要的值的二叉搜索程序
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- C++:用户输入会产生不需要的行为
- 如何在不需要LIBCD.lib的情况下在Visual Studio 6中编译C项目
- 为什么python需要全局关键字而C/C++不需要?
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 为什么 std::cin 不提示用户输入?
- cin.ignore() 正在产生不需要的行为
- 为什么在"cin"后使用 "getline" 时需要 cin.ignore(),而多次使用 "cin" 时不需要?
- 在c++中使用cin.get()从输入流中丢弃不需要的字符