2011-12-12 60 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

謝謝。 :)它現在有效。 –

相關問題