<分区>
我想通过使用字符串变量询问用户的名字和姓氏,然后使用他们在该字符串中输入的名字并将其打印出来。
string name;
cout << "What is your first and last name? ";
cin >> name;
cout << "Thank you " << name << " for shopping with us!";
在第二个 cout 语句中 name 变量的位置我只想使用他们的名字,根据我当前的设置,它会输出他们的名字和姓氏。
标签 c++
<分区>
我想通过使用字符串变量询问用户的名字和姓氏,然后使用他们在该字符串中输入的名字并将其打印出来。
string name;
cout << "What is your first and last name? ";
cin >> name;
cout << "Thank you " << name << " for shopping with us!";
在第二个 cout 语句中 name 变量的位置我只想使用他们的名字,根据我当前的设置,它会输出他们的名字和姓氏。
最佳答案
您可以使用 getline 只占用第一个空格,将名字放在一个变量中,然后读取到另一个变量中姓氏的行尾。如果您需要将两者连接起来,请在之后进行。示例:
string first, last, name;
getline(cin, first, ' ');
getline(cin, last);
cout << "Thank you " << first << " for shopping with us!";
name = first + ' ' + last; //Assuming you want a space in between
关于C++,如何只打印出字符串的第一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762904/