from while loop to for loop -strings

Hey there,

i want to count the number of words on each line from an inputted file.

from an input the program will look like :
1
2
3
4
5
6
7
8
9
10
11
   cout << endl << "Enter a sentence in a line: " << endl;
   string a_line;
   getline(cin, a_line);
  
   int count = 0;
   istringstream src2(a_line);
   string a_word;
   while (src2 >> a_word)
     ++count;
   cout << "There are " << count << " words." << endl;


how can you convert it to a for loop? so that every line is read in the file?
I have not understood why is there necessary to use the for loop?

It is much simpler to write

1
2
3
4
5
6
7
8
int count = 0;
while ( std::getline( std::cin, line ) )
{
   count += std::distance( std::istream_iterator<std::string>( std::istringstream( line ) ), 
                           std::istream_iterator<std::string>() );
}

std::cout << "There are " << count << " words." << std::endl;
Last edited on
But im reading from a file ?
Then change std::cout to some ifstream. For example

1
2
3
4
5
std::ifstream file_stream( "MyFile" );

while ( std::getline( file_stream, line ) )
{
// ... 
Last edited on
closed account (3CXz8vqX)
For loops are generally used when you know the exact amount of numbers you are dealing with. Otherwise if you don't and in this case, you're recommended to use while loops, since you don't know how long it's going to take for the loop to end.

You 'could' use a for loop with some tweaking but it just makes for confusing syntax.
i was thinking the number of for loops determined by the no. of lines in the file ?
To count the number of lines in the file you have to read all the lines.:) So there is no any sense in such an operation even if the first line contains some number that is considered as the total number of lines. In any case it is better to use the while loop because it is possible that some errors will occur during reading lines.
Last edited on
Thank you :)
Topic archived. No new replies allowed.