Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

end of input getline [duplicate]

Tags:

c++

getline

input

Possible Duplicate:
Why doesn’t getchar() recognise return as EOF in windows console?

I have a simple problem... Lets say I want to read lines from standart input as long as there is something, but I dont know how many lines it will be. For example I am doing school work and input is

a
ababa
bb
cc
ba
bb
ca
cb

I dont know exactly how many lines it will be, so I tried

string *line = new string[100];
    int counter = 0;
   while(getline(cin,line[counter]))
   {
    counter++;
   }

But it doesn't work... thanks for help.

like image 221
user1751550 Avatar asked Nov 23 '12 18:11

user1751550


People also ask

What happens when Getline reaches end of file?

The alternative standard functions are unreliable. If an error occurs or end of file is reached without any bytes read, getline returns -1 .

Does Getline work with double?

cplusplus.com/reference/istream/istream/getline getline doesn't take a double argument, as it's telling you. it's there to get lines of data (aka char arrays / strings) not numbers. You want to use atoi or something similar.

How do I use Getline multiple times?

You can just use the static method tinyConsole::getLine() in replace of your getline and stream calls, and you can use it as many times as you'd like. Save this answer.

Does Getline stop at whitespace?

Using getline functionThe getline function reads in an entire line including all leading and trailing whitespace up to the point where return is entered by the user.


1 Answers

If you want input to end on an empty line then you have to test for it. For instance.

string *line = new string[100];
int counter = 0;
while (getline(cin, line[counter]) && line[counter].size() > 0)
{
    counter++;
}

Congrats for using getline() correctly BTW. Unlike some of the answers you've been given.

like image 115
john Avatar answered Oct 30 '22 22:10

john