我也想从具有字符串的文件中获取整数,并将其存储到数组中以对它们进行一些操作。整数可以是1或12或234,所以3位数字。我正在尝试执行此操作,但是在运行代码时输出停止]
void GetNumFromFile (ifstream &file1, char & contents)
{
int digits[20];
file1.get(contents);
while(!file1.eof())
{
for (int n = 0; n < 10; n++)
{
if(('0' <= contents && contents <= '9') && ('0' >= contents+1 && contents+1 > '9'));
digits[n]=contents;
if(('0' <= contents && contents <= '9') && ('0' <= contents+1 && contents+1 < '9'));
digits[n]=contents;
if(('0' <= contents && contents <= '9') && ('0' <= contents+1 && contents+1 <= '9') && ('0' <= contents+2 && contents+2 < '9'));
digits[n]=contents;
}
continue;
}
for (int i = 0; i <= 20; i++)
{
cout << *(digits + i) << endl;
}
}
第一次观察:您遍历数组的边界:
int digits[20];
for (int i = 0; i <= 20; i++)
20个元素和21个迭代。这是未定义的行为,因此一切皆有可能(如果您的程序最终到达这里)。
接着,您从文件中读取一次,然后出现无限循环,因为对于程序其余部分,表达式!file1.eof()
为true或false。这不是“输出停止”的原因吗?
第三项发现:您的if
语句无用,因为该语句后有分号:
if(('0' <= contents && contents <= '9') && ('0' >= contents+1 && contents+1 > '9'));
digits[n]=contents;
您只分配了digits[n]=contents;
而没有进行任何检查。
我都看不到在函数中提供对char的引用的任何原因。为什么不将其设置为局部变量?
您还需要先在循环内添加get()
功能才能到达文件末尾。
此外,一旦发现char
是整数以继续请求下一个字符,请尝试添加while循环。
例如
int digits[20];
int i = 0;
ifstream file1("filepath");
char contents;
while (!file1.eof())
{
file1.get(contents); // get the next character
if (contents <= '9' && contents >= '0' && i < 20) // if character is in number range
{
digits[i++] = contents - '0'; // converting the chat to the right integer
file1.get(contents);
while (contents <= '9' && contents >= '0' && i < 20) // while is integer continue on
{
digits[i++] = contents - '0';
file1.get(contents);
}
}
}
// do other stuff here
您必须处理找到的数字的位数:
int digits[20];
int i = 0;
short int aux[3]; // to format each digit of the numbers
ifstream file1("filepath");
char contents;
file1.get(contents); //first char
while (!file1.eof())
{
if (contents <= '9' && contents >= '0' && i < 20) // if character is in number range
{
aux[0] = contents - '0'; // converting the char to the right integer
file1.get(contents);
if ((contents <= '9' && contents >= '0' && i < 20) && !file1.eof()) // if is integer and has mor char to read, continue on
{
aux[1] = contents - '0';
file1.get(contents);
if ((contents <= '9' && contents >= '0' && i < 20) && !file1.eof()) // if is integer and has mor char to read, continue on
{
aux[2] = contents - '0';
file1.get(contents);
aux[0] *= 100; // define houndred
aux[1] *= 10; // define ten
digits[i++] = aux[0] + aux[1] + aux[2];
}
else
{
aux[0] *= 10; // define ten
digits[i++] = aux[0] + aux[1];
}
}
else
{
digits[i++] = aux[0];
}
}
i++;
}
如果要读取未定义的大小数字,则必须分配内存以用new(c ++)或malloc(c / c ++)格式化数字的每个数字。