[英]Read number from text file without whitespace
I am trying to read a 12 digit number from a text file in to an array. 我试图从文本文件中读取一个12位数字到一个数组。 I have been able to do this successfully if I place whitespace between each digit.
如果我在每个数字之间放置空格,我就能成功地做到这一点。 for instance:
例如:
1 1 1 1 1 1 1 1 1 1 1 1
But when I remove the whitespace between the digits my program is no longer able to allocate the array from the text file. 但是当我删除数字之间的空格时,我的程序不再能够从文本文件中分配数组。 for instance:
例如:
111111111111
I am sure the answer is simple but I have been unable to find the solution to my exact problem anywhere. 我确信答案很简单,但我无法在任何地方找到解决我的确切问题的方法。 Below is my while loop that I use to allocate the array.
下面是我用来分配数组的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();
}
To read an array of chars, supposing there are no spaces or other delimiters, you can read the whole of it from input stream at once: 要读取字符数组,假设没有空格或其他分隔符,您可以立即从输入流中读取整个字符:
in >> myarray;
To create an array of integers, you can read the input char by char and fill the array in place: 要创建整数数组,可以通过char读取输入char并填充数组:
char c;
int i = 0;
while( !in.eof())
{
in >> c;
myarray[ i++ ] = c - '0';
}
In this case there may be any quantity of spaces in any place, they will be ignored. 在这种情况下,任何地方都可能有任何数量的空间,它们将被忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.