空格后不打印单个单词

时间:2021-06-11 12:52:13

标签: c++ string

您好,我正在解决 Stanley 所著的 C++ Primer 一书中的一个问题。问题是:-

编写一个程序,一次读取标准输入一行。修改您的程序以一次读取一个单词。

我使用了选择变量,用户可以通过它切换到所需的输出,即是打印一行还是一个单词。 Line 输出是正确的。但是,单词输出并不正确。因为,我想在空格之前打印单词。但即使在空格之后它也会打印整个句子。

以下代码:-

 #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;
}

当我选择 w 时,我的输出如下:- enter image description here

我希望它只打印 shubharthak,因为我只使用 cout< 它不应该包含空格,并且只在空格之前打印字符。如果不是这种情况,那么为什么在编译以下程序时它会打印单个单词:-

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

  return 0;
}

如果我编译上面的程序,它会给出如下输出,它只会在空格前打印一个单词:- enter image description here

1 个答案:

答案 0 :(得分:0)

这是因为 while 循环。删除它,程序按预期工作。

#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;
}

结果:

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

相关:cin inside a while loop

另见Why is "using namespace std;" considered bad practice?