2011-11-21 32 views
2

我在編寫程序的一部分時會遇到問題,該程序將從文件中讀取名稱和10個數字。外商投資企業被稱爲grades.dat數據文件的結構是:如何在C++中分割一行並從中提取值?

Number One 
99 99 99 99 99 99 99 99 99 99 
John Doe 
90 99 98 89 87 90.2 87 99 89.3 91 
Clark Bar 
67 77 65 65.5 66 72 78 62 61 66 
Scooby Doo 
78 80 77 78 73 74 75 75 76.2 69 

這是我的所有的函數來獲取數據,我甚至不知道這是正確的。

void input (float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname) 
{ 
    ifstream infile; 

    infile.open ("grades.dat"); 
    if (infile.fail()) 
    { 
     cout << "Could not open file, please make sure it is named correctly (grades.dat)" << "\n" << "and that it is in the correct spot. (The same directory as this program." << "\n"; 
     exit(0); 
    } 
    getline (infile, studentname); 
    return; 
} 
+3

'90.2'不是一個整數。你的意思是它應該是一個名字,然後是十個*數字*?如果不是,你的程序如何處理畸形輸入? – meagar

+0

是的,是我的錯。編輯的問題。謝謝 –

回答

10

使用標準的C++成語,讀兩行時間(或失敗,如果這是不可能的):

#include <fstream> 
#include <sstream> 
#include <string> 

#include <iterator> // only for note #1 
#include <vector> //  -- || -- 

int main() 
{ 
    std::ifstream infile("thefile.txt"); 
    std::string name, grade_line; 

    while (std::getline(infile, name) && std::getline(infile, grade_line)) 
    { 
     std::istringstream iss(grade_line); 

     // See #1; otherwise: 

     double d; 

     while (iss >> d) 
     { 
      // process grade 
     } 
    } 
} 

注:如果他內環唯一的目的(標#1 )是存儲所有的等級,然後根據@Rob建議你可以使用流迭代器:

std::vector<double> grades (std::istream_iterator<double>(iss), 
          std::istream_iterator<double>()); 

流迭代器做同樣的事情作爲內while環以上,即它迭代了double類型的標記。您可能希望將整個矢量插入一個容納名稱和等級對的大容器中。

+0

它如何知道哪一行讀取哪個變量? –

+2

或'std :: vector v((std :: istream_iterator (iss)),std :: istream_iterator ());'而不是while while循環。 –

+2

@Sam - '&&'操作符執行從左到右。所以它首先讀取'name',然後(只有當讀取'name'成功時)它讀取'grade_line'。 –

相關問題