use*_*388 2 c++ string file-io atoi
我从文件中读取了一行,我试图将其转换为int.由于某种原因atoi()
(将字符串转换为整数)将不接受std::string
作为参数(可能是字符串与c字符串与字符数组的问题?) - 如何atoi()
正确工作以便我可以解析此文本文件?(将从中抽出大量的金额).
码:
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;
}
Run Code Online (Sandbox Code Playgroud)
引起问题的线是:
int columns = atoi(line);
Run Code Online (Sandbox Code Playgroud)
这给出了错误:
错误:无法转换
'std::string'
到'const char*'
的参数"1"到"廉政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;
}
Run Code Online (Sandbox Code Playgroud)
还想知道为什么string filename ="data.txt"; ifstream文件(文件名)失败,但是
ifstream file("data.txt");
Run Code Online (Sandbox Code Playgroud)
作品?(我最终将从命令行读取文件名,因此需要使其不是字符串文字)
为此目的存在c_str方法.
int columns = atoi(line.c_str());
Run Code Online (Sandbox Code Playgroud)
BTW您的代码应该阅读
while (getline (file,line))
{
...
Run Code Online (Sandbox Code Playgroud)
仅仅因为文件"好"并不意味着下一个 getline会成功,只是最后一个 getline成功了.在您的while条件下直接使用getline来判断您是否确实读过一行.
归档时间: |
|
查看次数: |
22507 次 |
最近记录: |