2015-01-11 3 views
3

저는 C++의 초보자입니다. 따라서 제게 열심히 판단하지 마십시오. 아마도 이것은 바보 같은 질문이지만 알고 싶습니다.줄 단위로 읽는 방법

내가이 같은 텍스트 파일이 (항상 4 개 개의 숫자 수 있지만 행의 수는 달라질 수 있습니다) : 여기

5 7 11 13 
11 11 23 18 
12 13 36 27 
14 15 35 38 
22 14 40 25 
23 11 56 50 
22 20 22 30 
16 18 33 30 
18 19 22 30 

과 내가 원하는 무엇인가 : 을 내가 이것을 읽고 싶어 줄 단위로 파일을 만들고 각 숫자를 변수에 넣으십시오. 그렇다면이 4 개의 숫자로 몇 가지 기능을 수행하고 다음 줄을 읽고이 4 개의 숫자로 몇 가지 기능을 다시 수행하겠습니다. 내가 어떻게 할 수 있니? 내가

#include <iostream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    int array_size = 200; 
    char * array = new char[array_size]; 
    int position = 0; 

    ifstream fin("test.txt"); 

    if (fin.is_open()) 
    { 

     while (!fin.eof() && position < array_size) 
     { 
      fin.get(array[position]); 
      position++; 
     } 
     array[position - 1] = '\0'; 

     for (int i = 0; array[i] != '\0'; i++) 
     { 
      cout << array[i]; 
     } 
    } 
    else 
    { 
     cout << "File could not be opened." << endl; 
    } 
    return 0; 
} 

을 모르지만, 이런 식으로 내가 배열에 전체 파일을 읽고있다,하지만 난, 줄 단위로 읽어 내 기능을 수행하고 다음 라인을 읽을 수로 이것은까지입니다.

+0

제 판독 [_Why이다 iostream :: EOF 잘못 간주 루프 조건? _ 내부 (http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition -considered-wrong) 그런 다음 [std :: getline()] (http://en.cppreference.com/w/cpp/string/basic_string/getline)에 대해 읽으십시오. –

답변

2

파일에서 데이터를 읽으려면 stringstream이 정말 도움이된다는 것을 발견했습니다.

어때?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    ifstream fin("data.txt"); 
    string line; 

    if (fin.is_open()) { 
    while (getline (fin,line)) { 
     stringstream S; 
     S<<line; //store the line just read into the string stream 
     vector<int> thisLine(4,0); //to save the numbers 
     for (int c(0); c<4; c++) { 
     //use the string stream as a new input to put the data into a vector of int  
     S>>thisLine[c]; 
     } 
     // do something with these numbers 
     for (int c(0); c<4; c++) { 
     cout<<thisLine[c]<<endl; 
     } 
    } 
} 
else 
{ 
    cout << "File could not be opened." << endl; 
} 
return 0; 
} 
+0

고마워, 나는 앞으로 나아 간다;) – user3668051

관련 문제