文件中的C++cin取消数字的空格

C++ cin from a file unspaced numbers

本文关键字:数字 空格 取消 C++cin 文件      更新时间:2023-10-16

在c++中,如何生成一个不按数组分隔的数字文件?

例如78940725450327458,我如何才能将这些数字放置为list[0]=7,list[1]=8,list[2]=9,依此类推。

std::vector<int> numList;
while(std::cin) {
    char c;
    std::cin >> c;
    if(std::cin.eof())
        break;
    if(c < '0' || c > '9') {
        // handle error
    }
    numList.push_back(c - '0');
}

将列表列为char s的数组。

CCD_ 2将读取单个字符。

我建议您将所有行读取到int变量中,然后使用以下内容进行循环:

int temp = a % 10;

每次都会给你最后一个数字,之后一定要更新原始数字,最后一件事就是把它放进数组,所以这是容易的部分。

有很多方法可以做到这一点。我可能会做以下事情:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
int ascii2int(int value) // this could be a lambda instead
{
    return value - '0';
}
int main()
{
    std::vector<int> nums;
    std::ifstream input("euler8Nums.txt");
    if (input)
    {
        // read character digits into vector<int>
        nums.assign(std::istream_iterator<char>(input), std::istream_iterator<char>());
        // transform ascii '0'..'9' to integer 0..9
        std::transform(nums.begin(), nums.end(), nums.begin(), ascii2int);
    }
    // your code here
    return 0;
}