【发布时间】:2013-05-02 19:37:29
【问题描述】:
我从文件中读取了一行,我正在尝试将其转换为 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;
}
导致问题的行是:
int columns = atoi(line);
给出错误:
错误:无法将参数 '1' 的
'std::string'转换为'const char*'到 '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,没错,但你的意思是
strtol。boost::lexical_cast也可能是一个选项。 有一个关于IIRC某处所有这些的问题。 -
atoi 不报告错误似乎是有益的,即使出现问题,它也会尝试工作,而不是向我抛出异常并退出。从www.cplusplus.com,发现atoi很好,因为“No-throw保证:这个函数永远不会抛出异常。”
-
@user2333388,这很糟糕。这意味着您不知道它是否成功,您是否想知道。如果你想忽略错误的转换,你总是可以添加一个空的 catch 块。大多数时候,假装它有效会痛苦地结束。
-
@user2333388: 是的,在你的程序中输入字符串的人会喜欢它,因为它默默地使用 0 而不是他们想要给出的任何值,并且只是创建了一个类型,他们肯定不会想知道为什么哎呀,程序没有按照他们的意图做。