Shubharthak
Shubharthak

Reputation: 31

Not printing single word after whitespace

Hi I am solving a question of book C++ Primer by Stanley. The question is :-

Write a program to read standard input a line at a time. Modify your program to read a word at a time.

I have used select variable through which user can switch to desired output i.e whether to print a line or a word. The Line output is coming right. But, the word output is not coming right. As, I want to print word before space. But it's printing whole sentence even after whitespaces.

Code below :-

 #include<iostream>
using namespace std;
int main(){
  char select;
  string line,word;
  cout<<"please enter w(word) or l(line)";
  cin>>select;
  if(select=='l'){
  /* program to read one line at a time */
  while(getline(cin,line)){
    cout<<line;
  }
  }
  else if(select=='w'){
  /*program to read one word at a time */
  while(cin>>word){
    cout<<word;
  }
  }
  else {
    cerr<<"you have entered wrong input!"<<endl;
    return -1;
  }
  
  return 0;
}

my output is coming is as follows when I'm selecting w :- enter image description here

I want it to print only shubharthak as I am only using cout<<word; It should not include whitespaces and only print characters before whitespaces. If this is not the case then why It print single word when I compile the following program :-

#include<iostream>
using namespace std;
int main(){
  string s;
  cin >> s;
  cout << s;

  return 0;
}

if I compile the above program, it will give output as follows,it will only print single word before whitespace :- enter image description here

Upvotes: 1

Views: 340

Answers (1)

silverfox
silverfox

Reputation: 1662

It's because of the while-loop. Remove it and the program work as expected.

#include<iostream>
using namespace std;
int main()
{
    char select;
    string line,word;
    cout<<"please enter w(word) or l(line)";
    cin>>select;
    if(select=='l')
    {
        while(getline(cin,line)) { cout<<line; }
    }
    else if(select=='w') { cin >> word; cout<<word; }
    else
    {
        cerr<<"you have entered wrong input!"<<endl;
        return -1;
    }

    return 0;
}

Result :

please enter w(word) or l(line)w
test1 test2 test3
test1

Related : cin inside a while loop

Also, see Why is "using namespace std;" considered bad practice?

Upvotes: 1

Related Questions