Link to home
Start Free TrialLog in
Avatar of cfans
cfans

asked on

cin question

I have a prety easy question, my mind is just drawing a blank though..

say I'm getting user input, but don't know how many strings they are putting in, how can I read until the end of the input..printing each element out seperately.

Example:
Enter Words: hello cat bird dog
Avatar of DrAske
DrAske
Flag of Jordan image

Is It a homework??
you can declare an array of characters
char input[SIZE];
then read the users' input
cin.getline(input,SIZE,'\n');
then use *strtok* function to tokenize it ..

Is that clear??
the easy way to tokenize *input* is:
while(char*token= strtok(input," ");token!=NULL; token = strtok(NULL," "))
                cout<<token<<endl; // printing each element seperately

regards, Ahmad;
Avatar of pcgabe
pcgabe

Ahmad, should that be a for-loop instead?  ^_^
If the input is on multiple lines, encapsulate the thing in a while-loop:

      cin.getline(input,SIZE);      //primes the pump, so to speak.
      while (strlen(input))            //while the length of 'input' is not zero...
      {
            //tokenizer
            for(char*token= strtok(input," ");token!=NULL; token = strtok(NULL," "))
                  cout<<token<<endl; // printing each element seperately
            //reads the next line (IMPORTANT)
            cin.getline(input,SIZE);
      }
Arrays and pointers are evil ;-)

Consider using std::string and std::istringstream for this.

Consider using the returned reference from getline as your while condition. It returns a reference to the cin istream, which has a bool operator which is false, when you hit EOF. Likewise, istream operator>> returns a reference to the istream, which you can test in a similar manner.
 
     string line;
     while (getline(cin,line))      
     {
          istringstream istr(line);  
          string token;
          while (istr >> token)
               cout << token << endl;
     }
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the points, but rstaveley should have got some points as well ...