2014-11-17 2 views
-1

을 Heres처럼 내 TEST.TXT 보이는 무엇을 : 나는 문자열은 다음 3 개 INT의 벡터를 만들 때 TEST.TXT의 정수에 읽고 싶은읽기 문자열

18 19 20 
21 22 23 
22 23 24 
23 24 25 
24 25 26 
25 26 27 
28 29 30 
29 30 31 

. 는 그 의미가 있다면, 그래서 출력처럼 보이는 벡터이다 :

18 19 20, 21 22 23, 22 23 24, 23 24 25, 24 25 26, 25 26 27, 28 29 30, 29 30 31 

Heres는 내 코드 :

#include "test.txt" 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <cctype> 
#include <vector> 

using namespace std; 
struct M 
{ 
    int x; 
    int y; 
    int z; 
}; 

int main(){ 
    ifstream file; 
    file.open("test.txt"); 
    string value; 
    M XYZ; 
    vector<M> Vec; 
    if (file){ 
    while (getline(file, value)){ 
     XYZ.x = stoi(value); 
     if (value == " ") 
     XYZ.y = stoi(value); 
     if (value == " ") 
     XYZ.z = stoi(value); 
    } 
    Vec.push_back(XYZ); 
    } 
    else 
    cout << "Error openning file." << endl; 
    for (int i = 0; i < Vec.size(); i++) 
    cout << Vec[i] << endl; 
    return 0; 
} 

내가 제대로의 getline과 stoi를 사용하고 있지만, 잘못 될 수 있다고 생각. 로직이 대부분 올바른 것처럼 보입니다. 미리 감사드립니다.

+2

... 그래서 무엇이 문제입니까? 귀하의 질문은 무엇인가? – Dai

+1

안녕하세요, StackOverflow에 오신 것을 환영합니다! 코드에 어떤 문제가 있는지 알려주십시오. 이것이 코드 개선 질문이라면 더 좋습니다. [CodeReview StackExchange] (http://codereview.stackexchange.com) –

+2

'while' 루프 안에있는 내용을'std :: stringstream ss;' http://www.dreamincode.net/forums/topic/95826-stringstream-tutorial/을보고'ss'를 사용하여'ss >> XYZ.x >> XYZ.y >> XYZ와 같이 구조체를 채 웁니다. .z;'이런 식으로 공백 등을 신경 쓸 필요가 없습니다. – vsoftco

답변

1

귀하의 코드 때문에 @ 조나단 포터 주석 무엇 지금은 작동하지 않습니다

while (getline(file, value)) 
{ 
     std::stringstream ss(value); // must #include <sstream> 
     ss >> XYZ.x >> XYZ.y >> XYZ.z; 
} 

발생하기 쉬운 것들을 적은 실수를해야 std::stringstream 사용.

+0

감사합니다. 그러나 내용을 인쇄하려고하면 오류가 발생합니다. 'std :: ostream {aka std :: basic_ostream }'lvalue to 'std :: basic_ostream &&'cout << Moves [i] << endl ; – user3602550

+0

'Moves [i]'가'struct'이기 때문입니다. 'cout << Moves [i] .x << Moves [i] .y << Moves [i] .z', or 구조체의 ostream & operator <<와 같은 각 요소를 따로 표시해보십시오. – vsoftco