c++ - 如何使用 C++ 在没有 readline 的情况下显示字符串中的多个单词?

标签 c++

我正在使用 Visual C++ 6.0,目前创建了一个程序,用于打印存储在字符串中的输出。

问题是当我用空格输入单词时,输出中只有第一个单词可见。

例子:

Enter your address: new york
new
Press any key to continue

我想要这个:

Enter your address: new york
new york
Press any key to continue

此外,我尝试使用 getline 但是当我输入单词时,它会先打印空格,然后将最后一个输出存储在当前输出之前。

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

void main()
{
  string address1;
  cout<<"Enter your address:";
  cin>> address1;
  // getline(cin, address1); code when using getline
  cout<<address1<<"\n";
}

最佳答案

你做的是正确的,但主要问题是你正在使用 cin 而你应该避免它并使用 getline(cin,address1) 因为 cin 只会接受一个单词,它不会接受您在空格后键入的任何内容。另一方面,getline(cin,address1) 可以接受一个完整的句子和空格

阅读评论并使用此代码

#include <iostream>
#include <string>

using namespace std;

int main()//using int main()
{

  string address1;

  cout<<"Enter your address:";

  //cin>> address1; Don't use it

  getline(cin, address1);//use this

  cout<<address1<<"\n";

  return 0;//returning an integer 0
}

关于c++ - 如何使用 C++ 在没有 readline 的情况下显示字符串中的多个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25523464/

相关文章:

c++ - 错误 : candidate function not viable: 'this' argument has type 'const' but method is not marked const

c++ - 常量和可变

c++ - GStreamer 失真取决于图像大小

c++ - 我怎么知道它是一个有效的 gdi 区域句柄?

C++ 将派生类存储在单个 vector 中,派生类不包含重新定义的方法

c++ - 相同生成器值的 std::normal_distribution 结果?

c++ - cuda 中 float 的基数排序与双调排序

c++ - 为什么我的代码说 109 不是素数?

c++ - QScrollArea 与动态调整 subWidgets

c++ - 添加字符串的空结尾