从文件中读取无限数量的数字,存储在数组中(无空格)

时间:2017-09-29 18:38:21

标签: c++ arrays vector

我想要读取包含此(示例)的文件:

194920392038122341

并将每个数字存储在整数数组中。例如,a [0]为1,a [1]为9,等等。

我尝试使用这样的东西来读取数字并将它们存储在一个数组中:

    int n = 0;
    vector<int> numbers; 

    ifstream in
    in.open("input.txt");

    while (in >> n)
    {
        numbers.push_back(n);
    }

    int* array = &numbers[0];

但是,出于某种原因,这不会从文件中读取个别数字。它将它们视为&#34; 12&#34;,&#34; 34&#34;,&#34; 35&#34;等

1 个答案:

答案 0 :(得分:0)

这是我将如何做到的:

char n = 0;
vector<int> numbers; 

ifstream in("input.txt");

while (in.get(n)) {
   if(std::isdigit(n) {
       numbers.push_back(n - '0');
   }
}

int* array = &numbers[0];