2010-10-15 70 views
1

我有這個從marks.txt文件讀取的代碼。C++:讀取表單文本文件並轉換爲int問題?

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

int main() { 
    string name,result; 
    int number1; 
    ifstream myfile ("marks.txt"); 
    if (myfile.is_open()) 
    { 
    while (!myfile.eof()) 
    { 
     getline (myfile,name,'\t'); 
     getline (myfile,result,'\t'); 
     stringstream(result) >> number1; 
     cout << number1; 


    } 

    myfile.close(); 

    } 

    else cout << "Unable to open file"; 

    return 0; 
} 

我marks.txt文件包括:

john 20 

但是,當我跑的程序。 Number1輸出是36.我怎樣才能轉換結果字符串int正確?

回答

2

請注意,您將\t(製表符)作爲分隔符傳遞給getline。你確定你在輸入文件中使用了一個標籤嗎?如果您使用空格或任何其他字符,則所有輸入將進入name並且您的result將爲空,這將使number1未定義。我懷疑這就是你無處不在的原因。

+0

是的。我有點想念。謝謝 – diehell 2010-10-15 21:44:53

相關問題