Chris Maness
Chris Maness

Reputation: 1688

C++ testing for \n

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;

    }

Any help would be most appreciated.

Upvotes: 0

Views: 436

Answers (2)

J&#246;rg Beyer
J&#246;rg Beyer

Reputation: 3671

for starters: use a std::string instead of the char array and choose useful variable names.

#include <iostream>
#include <string>

using namespace std;

int main() 
{
    for(string text;getline(cin, text);) {
        if (!text.empty()) {
            cout << text << endl;
        } else {
           break;
        }      
    } 
}

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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
    }
}

Upvotes: 3

Related Questions