2013-01-01 3 views
-2

나는 한 줄을 가져 와서 다른 종류의 변수 (표준 C++ 라이브러리 사용)로 나눌 수 있기를 원한다. 그래서이 입력 라인 :C++ - 주어진 문자열을 입력에서 다른 유형의 변수로 나누는 방법은 무엇입니까?

C 56 99.7 86.7 9000 

위해 이러한 변수에 공백 문자로 "폭발"윌 :

#define MAX_LINE 200 

char line[MAX_LINE]; 
cout << "Enter the line: "; 
cin.getline (line,MAX_LINE); 

:

Char 
std:string 
double 
double 
double 

이 내가 현재 지정된 입력을 처리하는 방법입니다 getline()과 같은 특수 함수가 있나요? 주어진 입력을 분리하고 이러한 입력을 변수에 (캐스팅 또는 이와 유사한 방식으로) 할당하는 데 사용할 수 있습니까?

+4

읽기. 그것은 스트림에서 형식화 된 추출에 대해 알려줍니다. –

+1

Tokenize you and string, try/catch 블록을 사용하여 원하는 데이터로 변환합니다. – user1929959

답변

2

사용 >> 연산자를 사용하면

#include <iostream> 

int main() 
{ 
    char c; 
    double d; 
    std::cin >> c >> d; 

    std::cout << "The char was: " << c << ", the double was:" << d;  
} 

당신은 그것을 here 대신의 getline()를 사용

0

>> IStream을 연산자를 사용에 대한 자세한 내용을보실 수 있습니다 원하는 것을 얻을 수 있습니다.

이 연산자의 오버로드가 있습니다 더에 당신의 C++ 책에

// Member functions : 

istream& operator>> (bool& val); 
istream& operator>> (short& val); 
istream& operator>> (unsigned short& val); 
istream& operator>> (int& val); 
istream& operator>> (unsigned int& val); 
istream& operator>> (long& val); 
istream& operator>> (unsigned long& val); 
istream& operator>> (float& val); 
istream& operator>> (double& val); 
istream& operator>> (long double& val); 
istream& operator>> (void*& val); 
istream& operator>> (streambuf* sb); 
istream& operator>> (istream& (*pf)(istream&)); 
istream& operator>> (ios& (*pf)(ios&)); 
istream& operator>> (ios_base& (*pf)(ios_base&)); 

// Global functions : 
istream& operator>> (istream& is, char& ch); 
istream& operator>> (istream& is, signed char& ch); 
istream& operator>> (istream& is, unsigned char& ch); 
istream& operator>> (istream& is, char* str); 
istream& operator>> (istream& is, signed char* str); 
istream& operator>> (istream& is, unsigned char* str); 

char ch; 
std:string str; 
double d; 

cin >> ch >> str >> d; 
+0

당신은 방금 그들을 쓰지 않고 링크를 부여 할 수있었습니다. –

관련 문제