\n的C ++测试 [英] C++ testing for \n

查看:104
本文介绍了\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 ++测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆