Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this loop will ever end

Tags:

c++

while-loop

Opening Again Edit : How to end this one

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> s;
    string word;

    while(cin >> word)
        {
            s.push_back(word);
        }



        for(auto i =0; i < s.size(); i++)
        {
            for(auto &c : s[i])
            c = toupper(c);
        }

        int j=1;
        for(auto c : s)
        {
              cout << c << " ";
              if(j%8==0)
              {
                  cout << "\n";
              }
              j++;
        }  
}
  1. Other method can be used like putting word != "end" or something like that in while loop but it will create and extra word which i dont want.

  2. I am not getting a thing why when i give space between two words like, Hello my name is james(in input) then why c++ treats it like different string and strors in different blocks of vector. I am new at c++ programming as you can see, but a old C programmer, not very old 3 month older, college guy.


This is an example from book c++ primer 5th edition. My question how this while loop will end I tried everything like enter, entering 0 there a many examples in this book like this.

int main()
{
      vector<unsigned> scores(11, 0);          
      unsigned grade;
      while (cin >> grade)
      { 
            if (grade <= 100) // handle only valid grades
            ++scores[grade/10];
      }

      for(auto c : scores)
      {
           cout << c << endl;
      }
}
like image 611
mukuljainx Avatar asked Mar 17 '23 15:03

mukuljainx


1 Answers

The expression cin >> grade yields false (when evaluated as boolean) if the input operation failed. This happens if you reach the end of the input (EOF) or if the itput could not be parsed as the according type. Since whitespace is skipped, hitting enter doesn't exit the loop. Since a zero is a valid unsigned number, that doesn't trigger loop exit either. Entering a letter would do the job, or the (OS-specific) key combo to signal EOF.

like image 124
Ulrich Eckhardt Avatar answered Mar 29 '23 02:03

Ulrich Eckhardt