porcupine
porcupine

Reputation: 43

Getting more lines from input in C++

I need to read lines from standard input, but I dont really know, how many it will be. I tried to do it with getline() and cin combined with a while loop, but it led to an infinite loop:

string line;
while( getline(cin, string) ){...}

or

string word;
while( cin >> word ){...}

it doesnt stops at the end of the input( the lines are coming at one time, so the user is hitting just one time the Enter key ).

Thanks for your help.

Upvotes: 0

Views: 762

Answers (3)

Werner Henze
Werner Henze

Reputation: 16726

Reading your comments you have a misunderstanding of "end of input".

When you start your program it waits for input from console, and if input is available it reads it. Initially your copy some strings to your console so your program takes this as input. But your program still keeps reading from the console because there was no "end of input". The program is still connected to the console.

You need to signal "end of input" to your program. On Windows you do this by pressing Ctrl+Z. On Linux you need to press Ctrl+D.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476950

The way you run your program, your input doesn't end, since the console can always provide more input. Your program behaves correctly, though perhaps not in the way you desire. That's because you have misunderstood your own desires.

What you are looking for is perhaps (but I can't be sure) for the program to end when either the input ends or when the input contains a blank line. This can be coded as follows:

int main()
{
    for (std::string line; std::getline(std::cin, line); )
    {
        if (line.empty())
        {
            std::cout << "Got blank line, quitting.\n";
            return 0;
        }

        // process line
    }

    std::cout << "End of input, quitting.\n";
    return 0;
}

Upvotes: 1

user4233758
user4233758

Reputation:

Your problem is reading from the console.

As your console does not put an EOF(end of file) when you enter an empty line.

You should try pipeing the input from a file to your program. This should end, when there is no more input.

Otherwise, just check if the string is empty, and break out of the loop, if it is empty.

Upvotes: 1

Related Questions