我正在尝试编写一个程序,逐行读取文件,并将每行的内容存储为单独的整数值。典型的线路可能如下所示:
7190007400050083
我的代码中的以下片段从文件中读取一行,其中包含数字:
std::ifstream file;
file.open("my_file_with_numbers");
std::string line;
file >> line;
我希望将字符串拆分为单独的值并将它们作为整数存储在向量中。我查遍了互联网,但没有找到解决方案。非常感谢您的帮助。
假设您想要每个数字一个值,您可以这样做
std::vector<int> vec(line.length());
std::transform(begin(line), end(line), begin(vec),
[](char const& ch)
{
return ch - '0';
});
对于输入字符串
"7190007400050083"
,您将得到向量{ 7, 1, 9, 0, 0, 0, 7, 4, 0, 0, 0, 5, 0, 0, 8, 3 }
。