2017-03-01 55 views
0

我在讀取文件輸入行時遇到問題。這是一個非常簡單的任務,我可以管理,但問題是輸入文件行可以由單詞和數字組成,然後我必須單獨讀取它們並將它們存儲在不同的變量中。讓我舉個例子(斜體):嘗試解析從輸入文件讀取的行

BOOK 100 
PENCIL  45 
LAPTOP 49 
SPOON    34 

無論Word和數字之間有多少空格,閱讀操作都可以工作。

我寫了這段代碼直接讀取行。但根據我放棄的信息,我不知道如何解析它們。

string fileName; 
     cout << "Enter the name of the file: "; 
     cin >> fileName; 

     ifstream file; 
     file.open(fileName); 

     while(file.fail()) 
     { 
      cout << "enter file name correctly:"; 
      cin >> fileName; 
      file.open(fileName); 
     } 

     string line; 
     int points; 


     while(!file.eof()) 
     { 
      getline(file, line); 
      stringstream ss(line); 

        *I do not know what to do here :)* 
        } 
+0

'eof()'是導致無盡的麻煩的原因。試試'while(std :: getline(file,line){... use line}' – BoBTFish

回答

3

但我不知道如何根據我放棄了信息解析。

那很簡單,見下面的例子:

std::stringstream ss("SPOON    34"); 
std::string s; 
int n; 
if (ss >> s >> n) { 
    std::cout << s <<"\n"; 
    std::cout << n <<"\n"; 
} 

輸出:

SPOON 
34 
0

您可以使用sscanf

char name[100]; 
int number; 
sscanf(line, "%s %d", name, &number); 
printf("%s, %d", name, number); 

現在我不確定這真的是C++ ish。像你已經開始使用stringstreams的替代方案。