从没有空格的文本文件中读取数字

Read number from text file without whitespace

本文关键字:文件 读取 数字 文本 空格      更新时间:2023-10-16

我试图从文本文件中读取12位数字到数组。如果我在每个数字之间放置空格,我已经能够成功地做到这一点。例如:

1 1 1 1 1 1 1 1 1 1 1 1 

但是当我删除数字之间的空格时,我的程序不再能够从文本文件中分配数组。例如:

111111111111

我确信答案很简单,但是我在任何地方都找不到解决我确切问题的方法。下面是我用来分配数组的while循环。

void int_class::allocate_array(std::ifstream& in, const char* file)
{
    //open file
    in.open(file);
    //read file in to array
    int i = 0;
    while( !in.eof())
    {
        in >> myarray[i];
        i++;
    }
    in.close();
}

要读取一个字符数组,假设没有空格或其他分隔符,您可以一次从输入流中读取整个字符数组:

in >> myarray;

要创建一个整数数组,您可以一个字符一个字符地读取输入,并在适当的位置填充数组:

char c;
int i = 0;
while( !in.eof())
{
   in >> c;
   myarray[ i++ ] = c - '0';
}

在这种情况下,可以在任何地方有任意数量的空格,它们将被忽略。