有几种方法可以从字符串中解析出整数值。
首先,让我们来解决你的循环:
int pos = 0;
while(std::getline(in, line) && pos < 100)
{
int value = 0;
// Insert chosen parsing method here
arr[pos++] = value;
}
下面是常用选项的不完全名单:
使用std::strtol
// Will return 0 on error (indistinguishable from parsing actual 0)
value = std::strtol(line.c_str(), nullptr, 10 );
使用std::stoi
// Will throw exception on error
value = std::stoi(line);
建立一个std::istringstream
并从中读取:
std::istringstream iss(line);
iss >> value;
if(!iss) {
// Failed to parse value.
}
使用std::sscanf
if(1 != std::sscanf(line.c_str(), "%d", &value))
{
// Failed to parse value.
}
现在,请注意在循环检查pos < 100
边界测试。这是因为您的阵列具有存储限制。实际上,你也用Read_Save
中的本地地图覆盖了全局地图,因此用一个更小的数组隐藏它,当函数结束时会丢失一个更小的数组。
使用标准库提供的其他容器类型,可以有一个任意大小的“数组”(实际上不是数组)。提供随机访问的有用的是std::vector
和std::deque
。让我们用向量和改变Read_Save
的定义是有点更加有用:
std::vector<int> Read_Save(std::istream & in)
{
std::vector<int> values;
std::string line;
for(int line_number = 1; getline(in, line); line_number++)
{
try {
int value = std::stoi(line);
values.push_back(value);
}
catch(std::bad_alloc & e)
{
std::cerr << "Error (line " << line_number << "): Out of memory!" << std::endl;
throw e;
}
catch(std::exception & e)
{
std::cerr << "Error (line " << line_number << "): " << e.what() << std::endl;
}
}
return values;
}
最后,该呼叫将变为:
std::ifstream in("file.txt");
std::vector<int> values = Read_Save(in);
你不能输入整数与'strcpy' – Raindrop7
的阵列,同时在'而(!in.peek()= EOF)'会的工作,并在阅读EOF陷阱之前,对你没有陷入EOF测试中,你可能会发现'while(getline(in,line,'\ n'))'更好,因为它为你节省了'peek',并且捕获了比只是EOF。 – user4581301