gpt4 book ai didi

c++ - 从文件中读取空格分隔的数字

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:10 24 4
gpt4 key购买 nike

std::vector<int> loadNumbersFromFile(std::string name)
{
std::vector<int> numbers;

std::ifstream file;
file.open(name.c_str());
if(!file) {
exit(EXIT_FAILURE);
}

int current;
while(file >> current) {
numbers.push_back(current);
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return numbers;
}

问题是它在 VS 2012 中运行良好,但在 Dev C++ 中它只读取文件中的第一个数字——while 循环只运行一次。怎么了?

它应该与 .txt 文件一起使用。数字输入应该是这样的:

1 3 2 4 5

最佳答案

这是一种更惯用的从文件中读取整数到 vector 中的方法:

#include <iterator>
#include <fstream>
#include <vector>

std::vector<int> loadNumbersFromFile(const std::string& name)
{
std::ifstream is(name.c_str());
std::istream_iterator<int> start(is), end;
return std::vector<int>(start, end);
}

关于c++ - 从文件中读取空格分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com