2017-11-04 11 views
0

나는 다음과 같은 C++ 코드를 한 : 문제왜 istringstream에서 데이터를 읽는 중 오류가 발생합니까?

#include <iostream> 
#include <string> 
#include <vector> 
#include <sstream> 
#include <iomanip> 
#include <cstring> 

using namespace std; 

int main() { 

    istringstream inSS; 
    string title; 
    string col1; 
    string col2; 
    string val; 
    int numCommas; 
    vector<string> stringData(); 
    vector<int> intData(); 

    cout << "Enter a title for the data:" << endl; 
    getline(cin, title); 
    cout << "You entered: " << title << endl << endl; 

    cout << "Enter the column 1 header:" << endl; 
    getline(cin, col1); 
    cout << "You entered: " << col1 << endl << endl; 

    cout << "Enter the column 2 header:" << endl; 
    getline(cin, col2); 
    cout << "You entered: " << col2 << endl << endl; 



    while (1) { 

    cout << "Enter a data point (-1 to stop input):" << endl; 
    getline(cin, val); 



    if(strcmp(val.c_str(), "-1") == 0) { 
     break; 
    } 

    inSS >> stringData >> intData; 



    cout << "Data string: " << stringData << endl; 
    cout << "Data integer: " << intData << endl; 

    } 

    return 0; 
} 

오류 :

main.cpp: In function 'int main()': main.cpp:46:9: error: no match for 'operator>>' (operand types are 'std::istringstream {aka std::cxx11::basic_istringstream<char>}' and 'std::vector<std::cxx11::basic_string<char> >()') 
inSS >> stringData >> intData; 
    ~~~^~~~~~~~~~~ 

이 오류가 무엇을 의미합니까? 어떻게 수정해야합니까?

+0

'stringData'는 벡터이고, 벡터는'>>'에 오버로드를 제공하지 않습니다. 'inSS >> stringData >> intData;'무엇을 기대합니까? – Carcigenicate

+0

상당히 간단합니다. 그것은 당신이 사용하고있는'operator >> 연산자가없는'basic_istringstream' (즉,'inSS')과'vector' (즉'stringData'와'intData')를 사용하고 있다는 것을 말하고 있습니다 inSS >> stringData >> intData;'). –

+0

그렇다면 어떻게 사용자 입력을 벡터에 저장합니까? 이 할당을 위해 우리는 istringstream과 벡터를 사용하기로되어 있습니다. – Chase

답변

0

오류는 여러 요인의 조합과 관련이 있습니다. 우선,의이 줄을 살펴 보자 :

여기
inSS >> stringData >> intData; 

, 당신은 vector<string>vector<int> 내로 istringstream에서 읽으려고하고 있습니다. 그러나 스트림 추출 연산자를 사용하여 스트림에서 vector을 읽을 수 없습니다. 근본적인 이유는 없습니다. 표준에서 허용하지 않는 것입니다. 한 번에 한 요소 씩 그 데이터를 읽어야 할 것이므로 많은 코드를 다시 작성해야 할 것입니다.

또 다른 미묘한 문제가 있습니다. 이 라인은 그들이 무슨 생각을하지 않는다 :

vector<string> stringData(); 
vector<int> intData(); 

가 기본 생성자를 사용하여 입력 vector<string>vector<int>stringDataintData라는 이름의 변수를 선언처럼이 선을 보인다. 불행하게도 C++은 이것을 믿을 지 아닌지를 함수 프로토 타입으로 해석합니다. 첫 번째 것은 인자가없는 (따라서 괄호 사이의 빈 공간) stringData이라는 함수의 프로토 타입이며, 예를 들어 vector<string>을 반환합니다. 이 문제를 해결하려면 괄호를 버립니다. 그냥

vector<string> stringData; 
vector<int> intData; 

이 요약 쓰기 :

  • 당신이 vector 내로 istringstream에서 읽을 수 없기 때문에 당신은 근본적으로 코드에 일부 내용을 변경해야합니다. 따라서 논리 업데이트가 필요합니다.
  • 괄호를 삭제하여 이전의 두 선언을 수정해야합니다.