简体   繁体   English

来自文件的C ++ Cin无空格数字

[英]C++ cin from a file unspaced numbers

In c++ how do i cin a file of numbers that are not spaced into an array? 在C ++中,我如何将未间隔成数字的数字文件分割成一个数组?

For instance 78940725450327458 how could i get those numbers to be placed so that list[0] = 7, list[1] = 8, list[2] = 9 and so on. 例如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');
}

Make list an array of char s. 使列表为char数组。

cin >> list[0] will then read a single character. cin >> list[0]将读取单个字符。

I would suggest you to read all the line into int variable and then do the loop with something like this: 我建议您将所有行读入int变量,然后使用类似以下的代码进行循环:

int temp = a % 10;

this will give you last number everytime, be sure to update original number after that and last thing to do is to put it into array, so thats the easy part. 这将每次都给您最后一个号码,请确保在此之后更新原始号码,最后要做的就是将其放入数组中,因此很简单。

There are many ways to do this. 有很多方法可以做到这一点。 I'd probably do something like the following: 我可能会执行以下操作:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM