2013-05-02 138 views
1

我已經從文件中讀取一行,我試圖將它轉換爲int。由於某種原因,atoi()(將字符串轉換爲整數)將不接受std::string作爲參數(可能與字符串vs c字符串vs char數組有關的一些問題?) - 我如何才能使atoi()正常工作,以便我可以解析此文本文件? (將會從中抽取很多整數)。不能讓atoi採取一個字符串(字符串與C字符串?)

代碼:

int main() 
{ 
    string line; 
    // string filename = "data.txt"; 
    // ifstream file(filename) 
    ifstream file("data.txt"); 
    while (file.good()) 
    { 
     getline(file, line); 
     int columns = atoi(line); 
    } 
    file.close(); 
    cout << "Done" << endl; 
} 

線造成的問題是:

int columns = atoi(line); 

這給錯誤:

error: cannot convert 'std::string' to 'const char*' for argument '1' to 'int atop(const char*) '

我怎麼做的atoi正常工作?

編輯:謝謝大家,它的作品!新代碼:

int main() 
{ 
string line; 
//string filename = "data.txt"; 
//ifstream file (filename) 
ifstream file ("data.txt"); 
while (getline (file,line)) 
{ 
    cout << line << endl; 
    int columns = atoi(line.c_str()); 
    cout << "columns: " << columns << endl; 
    columns++; 
    columns++; 
    cout << "columns after adding: " << columns << endl; 
} 
file.close(); 
cout << "Done" << endl; 
} 

也想知道爲什麼 字符串文件名= 「data.txt中」; ifstream的文件(文件名) 失敗,但

ifstream file("data.txt"); 

的作品? (我最終會被讀取文件名以命令行形式,以便需要使它不是一個字符串字面)

+3

永遠不要使用atoi。它不能報告錯誤。使用std :: strtoi,或者更好,std :: stoi。 – PlasmaHH 2013-05-02 19:39:08

+2

@PlasmaHH,的確如此,但你的意思是'strtol'。 'boost :: lexical_cast'也可能是一個選項。 *在這個地方有一個關於IIRC的問題。 – chris 2013-05-02 19:41:05

+0

atoi不報告錯誤似乎是有益的,即使出現問題,它也會嘗試工作,而不是向我拋出異常並退出。從www.cplusplus.com,發現atoi是好的,因爲「無丟包保證:這個函數永遠不會拋出異常。」 – user2333388 2013-05-02 19:53:01

回答

6

的c_str方法存在這個目的。

int columns = atoi(line.c_str()); 

BTW你的代碼應該閱讀

while (getline (file,line)) 
{ 
    ... 

只是因爲該文件是 '好' 並不意味着下一個函數getline會成功,只有那最後函數getline成功。直接在你的while條件中使用getline來判斷你是否真的讀了一行。

+0

它的作品 - 謝謝!順便說一句,任何想法爲什麼字符串文件名=「data.txt」; ifstream文件(文件名)失敗但是ifstream文件(「data.txt」);作品? – user2333388 2013-05-02 19:47:33

+1

相同的解決方案'ifstream file(filename.c_str());'雖然我認爲在C++ 11中也可以使用字符串。有一個從char *到字符串的自動轉換,但不是相反。這是字符串類的設計方式。 – john 2013-05-02 19:49:03

1

使用line.c_str(),而不是僅僅line

這的atoi需要const char*不是std::string

2

int columns = atoi(line.c_str());