Atoi() 未按预期工作

atoi() not working as expected

本文关键字:工作 Atoi      更新时间:2023-10-16
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
•
• //main func declaration etc...
•
//Vectors for storing information from file
vector<string> include;
vector<string> exclude;
string temp; //for storing whatever the stream is on
int len = atoi(puzzle_file >> temp); //first pos
int width = atoi(puzzle_file >> temp); //second pos

上面的代码应该读取一个文件并将数字存储在相应的整数中。我收到一个错误,说"调用'atoi'没有匹配函数",即使我的文件头中有 #include <\cstdlib>和 #include <\stdlib.h>。不知道从这里去哪里。对stackoverflow和其他论坛进行了一些研究,找不到任何真正帮助我的东西。有什么建议吗?谢谢

你应该使用stoi而不是atoi。

stoi采用std::string作为参数,而atoi采用const char*作为参数。

不要忘记stoi自 c++11 以来是新的。

puzzle_file >> temp表达式返回istream,但没有接受这种参数的atoi重载。

你应该打电话给atoi(temp.c_str());

您尝试跳过一条指令并丢失了。puzzle_file >> temp返回puzzle_file而不是temp.因此,您将atoi应用于转换为布尔值的输入流。用:

int len, width;
puzzle_file >> len >> width;
if (! puzzle_file)...