2011-12-12 57 views
0

我正在拼接名称的输入字符串的项目,由于某种原因,它不工作。它的一部分是从我的书中复制出来的代码,据说可以工作,所以我被卡住了。难道我做错了什么?为什么我的字符串不像它应该分裂?

#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; 
} 
+2

旁注:你知道吗,打印标签,你应该写'\ t'和不是你的字符串中的实际选项卡? – Shahbaz

+2

它是如何“不工作”,你给什么输入?什么是输出?什么是预期的输出? – Chad

+3

[main()的返回类型是'int',而不是'void'。](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main) –

回答

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; 
+0

谢谢。 :)它现在有效。 –

相关问题