简体   繁体   English

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

[英]How to display multiple words in string without readline using c++?

I'm using Visual C++ 6.0 and currently created a program that will print the output stored in string. 我正在使用Visual C ++ 6.0,当前创建了一个程序,该程序将打印存储在字符串中的输出。

The problem is when I entered words with space, only the first word is visible in the output. 问题是当我输入带空格的单词时,在输出中只有第一个单词可见。

Example: 例:

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

I want this: 我要这个:

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

Also, I tried to use getline but when I entered words, It will first print blank space then stored the last output before the current one. 另外,我尝试使用getline但是当我输入单词时,它将首先打印空白,然后将最后一个输出存储在当前输出之前。

Here's my code: 这是我的代码:

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

Use std::getline (std::cin, address1); 使用std::getline (std::cin, address1); , not cin. ,不是cin。 Because cin takes space as delimiter. 因为cin以空格作为分隔符。

What about this one? 这个如何? Kind of getline concept, presuming newline character is '\\n', change as required according to your platform, unix or windows etc getline概念的一种,假设换行符为'\\ n',根据您的平台,unix或windows等进行更改

int main()
{
  string addrpart, address1;
  cout<<"Enter your address:";
  cin>> addrpart;
  while (addrpart != "x") {
    address1 += addrpart + " ";
    addrpart = "x";
    cin>> addrpart;
  }
  cout<<address1<<"\n";
}

Here you go 干得好

#include <iostream>
#include <string>

using namespace std;

int main( int argc, char** argv )
{
  string userinput;

  cout << "Enter your address:";
  getline ( cin, userinput );
  cout << userinput;

  return 0;
}

$ g++ a.cpp -o app
$ ./app
Enter your address:new york
new york

you are doing it correct, but the main problem is that you are using cin while you should avoid it and use getline(cin,address1) because cin will only take a single word and it will not take anyhting which you type after space. 您做的正确,但是主要的问题是您在使用cin时应避免使用cin而应使用getline(cin,address1)因为cin只用一个单词,而不会在空格后键入任何内容。 On the other hand getline(cin,address1) can take a complete sentence along with spaces 另一方面, getline(cin,address1)可以使用完整的句子以及空格

Read the comments and use this code 阅读评论并使用此代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM