[英]simple cout then cin allowing whitespace example?
Looking for a simple getline example which works correctly. 寻找一个可以正常工作的简单getline示例。
I want to input something on the keyboard and assign it to a std::string, allowing for whitespace and tabs. 我想在键盘上输入一些内容,并将其分配给std :: string,以允许使用空格和制表符。 The delimiter is the carriage return. 分隔符是回车符。
TIA, Bert TIA,伯特
#include <string>
#include <iostream>
#include <ostream>
int main() {
std::string s;
std::cout << "Enter a line: ";
std::getline(std::cin, s);
std::cout << "You typed this: " << s << std::endl;
return 0;
}
Example run: 示例运行:
$ ./a.out Enter a line: foo bar You typed this: foo bar
An important note: after you use std::cin: 重要说明:使用std :: cin之后:
cin >> myVar;
The trailing newline is NOT removed. 尾随的换行符不会被删除。 You have to use getline twice 您必须两次使用getline
std::getline(std::cin, myString);
std::getline(std::cin, myString);
if you have previously extracted from cin, once for the newline, and once for the actual string. 如果您以前是从cin中提取的,则一次用于换行,一次用于实际字符串。 There are other ways to do this too. 还有其他方法可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.