C++:只读取多个输入到行尾
C++: Reading multiple inputs only to end of the line
这个程序应该如何工作:
Enter 4 words:
this is bad
Bad input.
和
Enter 4 words:
hello you love it
Good input.
我是如何尝试的:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
cout << "Enter 4 words:" << endl;
string a, b, c, d;
cin >> a >> b >> c >> d;
}
它在行尾读取输入,我不知道如何将它限制在一行。你能指出我应该使用什么功能吗?我将非常感谢您的每一个回答。
谢谢大家!
当程序的预期输入来自交互式终端时,应使用 std::getline()
。
这就是 std::getline()
的作用:它读取文本直到换行符。 operator>>
不会那样做,那是 std::getline()
所做的,那应该用来处理一行输入的文本。为正确的工作使用正确的工具。
可悲的是,许多 C++ 书籍和教程在介绍 std::getline()
之前过早地介绍了 >>
,并在示例中使用了它,只是因为 >>
更容易和更方便处理所需的数据类型转换。不幸的是,这导致了错误的心态,其中 >>
被认为是处理交互式输入的自动选择。不是。
正确的做法是使用std::getline()
。然后,如有必要,构造一个 std::istringstream
,并使用它来处理输入的任何类型转换。这不仅解决了眼前的问题,还解决了无法解析的输入将 std::cin
置于失败状态的问题,所有后续尝试的输入转换也都失败了——这是另一个常见的陷阱。
所以,使用std::getline()
,首先:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main(void) {
std::cout << "Enter 4 words:" << endl;
std::string line;
std::getline(std::cin, line);
现在,一旦输入文本行,就可以将其转换为 std::istringstream
:
std::istringstream i(line);
接着循环重复调用>>
来统计这一行的字数。这部分你可以自己完成。
P.S。另一个常见的陷阱是 using namespace std;
。 You should not do that, as well。越早获得良好的编程实践,后续通往 C++ 大师之路的道路就越容易。
您应该使用以下命令:
std::getline()
这将忽略最终的 space 作为引号终止字符串,您可以将值存储在变量中,然后查看其中有多少单词。
例子:
std::getline (std::cin,name);
这个程序应该如何工作:
Enter 4 words:
this is bad
Bad input.
和
Enter 4 words:
hello you love it
Good input.
我是如何尝试的:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
cout << "Enter 4 words:" << endl;
string a, b, c, d;
cin >> a >> b >> c >> d;
}
它在行尾读取输入,我不知道如何将它限制在一行。你能指出我应该使用什么功能吗?我将非常感谢您的每一个回答。
谢谢大家!
std::getline()
。
这就是 std::getline()
的作用:它读取文本直到换行符。 operator>>
不会那样做,那是 std::getline()
所做的,那应该用来处理一行输入的文本。为正确的工作使用正确的工具。
可悲的是,许多 C++ 书籍和教程在介绍 std::getline()
之前过早地介绍了 >>
,并在示例中使用了它,只是因为 >>
更容易和更方便处理所需的数据类型转换。不幸的是,这导致了错误的心态,其中 >>
被认为是处理交互式输入的自动选择。不是。
正确的做法是使用std::getline()
。然后,如有必要,构造一个 std::istringstream
,并使用它来处理输入的任何类型转换。这不仅解决了眼前的问题,还解决了无法解析的输入将 std::cin
置于失败状态的问题,所有后续尝试的输入转换也都失败了——这是另一个常见的陷阱。
所以,使用std::getline()
,首先:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main(void) {
std::cout << "Enter 4 words:" << endl;
std::string line;
std::getline(std::cin, line);
现在,一旦输入文本行,就可以将其转换为 std::istringstream
:
std::istringstream i(line);
接着循环重复调用>>
来统计这一行的字数。这部分你可以自己完成。
P.S。另一个常见的陷阱是 using namespace std;
。 You should not do that, as well。越早获得良好的编程实践,后续通往 C++ 大师之路的道路就越容易。
您应该使用以下命令:
std::getline()
这将忽略最终的 space 作为引号终止字符串,您可以将值存储在变量中,然后查看其中有多少单词。
例子:
std::getline (std::cin,name);