我已經從文件中讀取一行,我試圖將它轉換爲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 'intatop(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");
的作品? (我最終會被讀取文件名以命令行形式,以便需要使它不是一個字符串字面)
永遠不要使用atoi。它不能報告錯誤。使用std :: strtoi,或者更好,std :: stoi。 – PlasmaHH 2013-05-02 19:39:08
@PlasmaHH,的確如此,但你的意思是'strtol'。 'boost :: lexical_cast'也可能是一個選項。 *在這個地方有一個關於IIRC的問題。 – chris 2013-05-02 19:41:05
atoi不報告錯誤似乎是有益的,即使出現問題,它也會嘗試工作,而不是向我拋出異常並退出。從www.cplusplus.com,發現atoi是好的,因爲「無丟包保證:這個函數永遠不會拋出異常。」 – user2333388 2013-05-02 19:53:01