不能让 atoi 接受字符串(字符串与 C 字符串?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16346332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't make atoi take in a string (string vs. C-string?)
提问by user2333388
I have read a line from a file and I am trying to convert it to an int. For some reason atoi()
(convert string to integer) won't accept a std::string
as an argument (possibly some issue with strings vs c-strings vs char arrays?) - how do I get atoi()
to work right so I can parse this text file? (going to be pulling lots of ints from it).
我从文件中读取了一行,并且正在尝试将其转换为 int。出于某种原因atoi()
(将字符串转换为整数)不会接受 astd::string
作为参数(可能是字符串与 c 字符串与字符数组的一些问题?) - 我如何atoi()
才能正常工作以便我可以解析这个文本文件?(将从中提取大量整数)。
Code:
代码:
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;
}
The line causing problems is:
导致问题的线路是:
int columns = atoi(line);
which gives the error:
这给出了错误:
error: cannot convert
'std::string'
to'const char*'
for argument '1' to 'intatop(const char*)
'
错误:无法转换
'std::string'
到'const char*'
的参数“1”到“廉政atop(const char*)
”
How do i make atoi work properly?
我如何使 atoi 正常工作?
EDIT: thanks all, it works! new code:
编辑:谢谢大家,它有效!新代码:
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;
}
also wondering why string filename = "data.txt"; ifstream file (filename) fails, but
还想知道为什么 string filename = "data.txt"; ifstream 文件(文件名)失败,但是
ifstream file("data.txt");
works? ( I will eventually be reading filename form the command line so need to make it not a string literal)
作品?(我最终将从命令行读取文件名,因此需要使其不是字符串文字)
回答by john
The c_str method exists for this purpose.
为此目的存在 c_str 方法。
int columns = atoi(line.c_str());
BTW your code should read
顺便说一句,您的代码应该阅读
while (getline (file,line))
{
...
Just because the file is 'good' does not mean the nextgetline will succeed, only that the lastgetline succeeded. Use getline directly in your while condition to tell if you did actually read a line.
仅仅因为文件“好”并不意味着下一个getline 会成功,只是最后一个getline 成功。直接在你的 while 条件中使用 getline 来判断你是否真的阅读了一行。
回答by nullptr
int columns = atoi(line.c_str());
int columns = atoi(line.c_str());
回答by olevegard
Use line.c_str()
instead of just line
使用line.c_str()
而不仅仅是line
This atoi takes a const char*
not a std::string
这个 atoi 需要一个const char*
不是一个std::string