2011-12-12 9 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()의 리턴 타입은'void'가 아니라'int'입니다.] (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

감사합니다. :) 그것은 지금 작동합니다. –

관련 문제