2016-11-12 7 views
0

私はテキストファイルを解析しようとしています。私は単語を区切るためにスペースを使用しています。ここでは、テキストファイルの外観を示します。テキストファイルを解析する方法C++?

123456789 15.5 3 40.0 

この形式では約15行あります。今すぐ使用

int sin = stoi(line.substr(0, line.find(' '))); 

私は最初の2つの単語を分離することができますが、残りの部分は分離できませんか?

const char * IN_FILE = "EmployeePayInput.txt"; 

    // A second way to specify a file name: 
    #define OUT_FILE "EmployeePayOutput.txt" 

int main() 
    { 


ifstream ins; 
     ins.open(IN_FILE); 
     //Check that file opened without any issues 
     if (ins.fail()) 
    { 
     cerr << "ERROR--> Unable to open input file : " << IN_FILE << endl; 
     cerr << '\n' << endl; 
     _getch(); // causes execution to pause until a char is entered 
     return -1; //error return code 
    } 

    //Define ofstream object and open file 
    ofstream outs; 
    outs.open(OUT_FILE); 

    //Check that file opened without any issues 
    if (outs.fail()) 
    { 
     cerr << "ERROR--> Unable to open output file : " << OUT_FILE << endl; 
     cerr << '\n' << endl; 
     _getch(); // causes execution to pause until a char is entered 
     return -2; //error return code 
    } 

    // Process data until end of file is reached 
    while (!ins.eof()) { 
     string line; 


     while (getline(ins, line)) { 
      Employee e; 


      int sin = stoi(line.substr(0, line.find(' ')));//prints and stores the first item in sin 
      e.setSin(sin); 
      cout << sin << endl; 
      float hourly = stof(line.substr(line.find(' '))); 
      cout << hourly << endl;//prints and stores the second item in hourly 
      e.setPayRate(hourly); 
      int exemption = stof(line.substr(line.find(' '))); //doesn't do anything, I need to read the next item in the same line 
       cout << exemption << endl; 

     } 
    } 


    // Close files 
    ins.close(); 
    outs.close(); 

    cout << '\n' << endl; 

    // Remove following line of code (and this comment) from your solution 
    cout << "Type any key to continue ... \n\n"; 

    _getch(); // causes execution to pause until char is entered 
    return 0; 
} 

答えて

0

私はこのようにあなたの入力ロジックを書き換えます:line.substr(line.find(' ')は最初' 'の位置から行の残りの部分を取り、あなたの特定の問題については

// Process data until end of file is reached 
string line; 
while (getline(ins, line)) { 
    std::istringstream iss(line); 
    if (iss >> sin >> hourly >> exemption) { 
     Employee e; 
     e.setSin(sin); 
     e.setPayRate(hourly); 
     cout << exemption << endl; 
    } 
} 

lineはこの操作では変更されないため、2回目に呼び出すと同じ結果が得られます。

関連する問題