本文介绍了\n的C ++测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试学习C ++,一种练习是构建一个命令行工具,该工具接受用户输入并将其存储在char数组中,直到用户输入空白行为止。我认为我的骨骼是正确的,但是无论出于何种原因,我的身体都在不断运转。我的代码如下:
I'm attempting to learn C++ and one exercise is to build a command line tool that accepts user input and stores it in a char array until the user enters a blank line. I think I have the skeleton right but for whatever reason my while runs continuously. My code is as follows:
char a[256]; //while the first character isn't a new line while (a[0] != '\n') { //get the char array cin >> a; cout << a; }任何帮助将不胜感激。
推荐答案使用 operator>> 无法检测到换行符。对于大多数类型,它使用空格作为分隔符,并且不区分空格,制表符或换行符。改用getline:
You can't detect newlines with operator>>. For most types, it uses whitespace as a delimiter, and it doesn't differentiate between spaces, tabs or newlines. Use getline instead:
for (std::string line; std::getline(std::cin, line); ) { if (line.empty()) { // if the line is empty, that means the user didn't // press anything before hitting the enter key } }更多推荐
\n的C ++测试
发布评论