我正在研究一个拼接输入的名字字符串的项目,由于某种原因它无法正常工作。部分内容是从我的书中复制的代码,据说可行,所以我卡住了。我做错了吗?
#include <iostream>
#include <string>
using namespace std;
void main()
{
string name;
int index;
cout<<"Please enter your full name. ";
cin>>name;
cout<<"\n"<<endl;
index = name.find(' ');
cout<<"First Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
index = name.find(' ');
cout<<"Middle Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
cout<<"Last Name: "<<name<<" "<<name.length()<<endl;
}
答案 0 :(得分:7)
大多数人的名字至少由两个单词组成。这只会得到其中一个:
cout<<"Please enter your full name. ";
cin>>name;
istream operator>>
是以空格分隔的。改为使用getline:
std::getline(std::cin, name);
出于您的目的,您可以这样做,这更简单:
std::string first, middle, last;
std::cin >> first >> middle >> last;