gpt4 book ai didi

c++ - while循环在读取文件时陷入无限循环,无法移动到下一行

转载 作者:太空宇宙 更新时间:2023-11-04 12:59:34 26 4
gpt4 key购买 nike

我有一个程序,我必须在其中读取文件,如果来自文件的输入无效,我必须跳过该行,但我不知道该怎么做。这是我程序的一部分;

int main ()
{

int line=0;

ifstream infile; //INPUT input file stream
ofstream outfile; //OUTPUT output file stream

infile.open("inputPartd.txt");
if (! infile)
{
cout <<"Problem opening input file inputPartd.txt"<<endl;
return 1; //not successful
}

outfile.open("resultsPartd.txt");
if (! outfile)
{
cout <<"Problem opening output file resultsPartd.txt"<<endl;
return 1; //not successful
}



while (true)
{
double num1;
double num2;

int intnum1;
int intnum2;

char mathOperator;

double addition;
double subtraction;
double multiplication;
int division; //division is using remainders so float isnt needed
double power;

double remainder;

line = line +1;


//reading numbers from the file
if (infile >> num1 >> num2 >> mathOperator)
{}

else
{
cout << "INVALID OPERAND";
continue;
}


if(infile.eof())
break;
if(infile.fail())
{
// report error
break;
}

我的程序一直显示“INVALID OPERAND”,所以我想弄清楚如何从那里转到下一行,我们将不胜感激。

这是我的输入:

10 a +
what is this
25 35 -
-1 -1 *
9 6 /
0 1 /
1 0 /
2 4 !
2 4 more!
2 3 ^
2.0 3 ^
2 0.5 ^
0 1 ^
0.0 0.0 ^
10.0 5 +
10.5 5 +
3 2 x
-10000 -10000 *
3.14159 3.14159 *
3 3 /
0.0 0.0 /
32 0.2 ^
1 1 plus

最佳答案

输入的规则是怎样的?

10 a +

一样
10
a
+

假设它们不是,那么最简单的方法是将行解析与 token 解析分开。

使用 std::getline( std::istream, string ); 你可以读取整行。然后尝试用格式解析它。

这确保即使您不理解数据,您也会不断地吃掉输入。

Putting the read line into a `stringstream` allows the line to be parsed with similar code.


while (true)
{
double num1;
double num2;

int intnum1;
int intnum2;

char mathOperator;

double addition;
double subtraction;
double multiplication;
int division; //division is using remainders so float isnt needed
double power;

double remainder;
std::string strResult;
std::getline( infile, strResult );
std::stringstream currentLine( strResult );
line = line +1;


//reading numbers from the file
if (currentLine>> num1 >> num2 >> mathOperator)
{}

else
{
cout << "INVALID OPERAND";
// continue; <<< This doesn't help, as it goes to the beginning of the while loop, not allowing for eof / fail checks.
}


if(infile.eof())
break;
if(infile.fail())
{
// report error
break;
}

关于c++ - while循环在读取文件时陷入无限循环,无法移动到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com