C++ 用于从用户获取字符串中的多个单词的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4825483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:39:40  来源:igfitidea点击:

Code for getting multiple words in a string from user

c++cstring

提问by hkasera

Actually i want the user to enter a line of string having multiple wordsin it for example "My name is ABC". What is the C/C++ code for this purpose?

实际上我希望用户输入一行包含多个单词的字符串,例如“我的名字是 ABC”。用于此目的的 C/C++ 代码是什么?

Thanks in advance

提前致谢

回答by nybbler

Try using something like this snippet:

尝试使用类似以下代码段的内容:

string testString;

getline(cin, testString);

回答by wilhelmtell

#include<string>and see std::getline().

#include<string>并看到std::getline()

回答by CodeRain

You can use std::getline()to get a line from std::cin.

您可以使用std::getline()std::cin.

#include <iostream>
#include <string>
using namespace std;

int main () 
{
  string name;
  cout << "Enter Name: ";
  getline (cin,name);
  cout << "You entered: " << name;
}

回答by Richie Flores

#include<iostream>
#include<string> 
using namespace std;

int main(){

string testString;
getline(cin, testString);

{

if you have

如果你有

cin >> otherVariables

You need to delete the newline buffer in between by adding:

您需要通过添加以下内容来删除中间的换行缓冲区:

cin.ignore()

You should have something like:

你应该有类似的东西:

string userMessage;
cin.ignore();
getline(cin, testString);

回答by Chaitanya Shejwal

Following code will help you receive multiple names from user.

以下代码将帮助您从用户那里接收多个名称。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name[6];
    cout << "\nEnter your name : ";
    for(int i = 0; i < 6; i++)
    {
        getline(cin, name[i]);
    }
    for(int i = 0; i < 6; i++)
    {
        cout << "\nYou entered : " << name[i];
    }
    return 0;
}