End of getline input

Possible duplicate:
Why does not getchar () recognize return as EOF in the Windows console?

I have a simple problem ... Suppose I want to read lines from standard input if there is something, but I do not know how many lines it will be. For example, I do school work and introduce

a ababa bb cc ba bb ca cb 

I don’t know exactly how many lines there will be, so I tried

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

But that will not work ... thanks for the help.

+4
source share
5 answers

If you want the input to end on an empty line, you need to check it. For instance.

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

Congratulations on using getline() BTW properly. Unlike some of the answers you were given.

+4
source

You can get the number of rows with something like:

  string *line = new string[SIZE]; int lines = 0; while(lines < SIZE && getline(cin, line[lines]) && line[lines].size() > 0) { cout << input_line << endl; lines++; } 

Be sure to check to see if you are adding more rows than the size that the row of rows can handle, otherwise you might get a segmentation error.

+1
source

The simplest line counter that I can think of would be something like this:

 #include <string> #include <iostream> unsigned int count = 0; for (std::string line; std::getline(std::cin, line); ) { ++count; } std::cout << "We read " << count << " lines.\n"; 

Test:

 echo -e "Hello\nWorld\n" | ./prog 

If you want to discard empty lines, say if (!line.empty()) { ++count; } if (!line.empty()) { ++count; } instead.

+1
source

You can also use the end of file marker for this. Its use is as follows:

 std::ifstream read ("file.txt") ; while(!read.eof()) { //do all the work } 

This function returns true if the end of the file is reached. Thus, this will continue until you come across this.

Edit:

As mentioned in the comments, the eof method can be dangerous and does not produce the desired result. Thus, there is no guarantee that it will work in every case. You can see here when this can happen.

Read from a text file until EOF repeats the last line

0
source

This should work:

 int cont = 0; string s; while(cin >> s) { //while(getline(cin,s)) if needed if(s.empty()) break; ++cont; } 
0
source

Source: https://habr.com/ru/post/1448008/


All Articles