用C ++读取输入文本文件中的所有数据 [英] Reading all the data in a input text file in C++

查看:103
本文介绍了用C ++读取输入文本文件中的所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码来获取输入文本文件中的所有表达式并进行计算。但问题是,它只是计算第一个表达式。而且如果我在文本文件中包含---------来分隔表达式,它会给我编译错误。



我是什么尝试过:



i have have written a code to to take all expressions in an input text file and calculate them. But the problem is, it is only calculating the first expressions. And also if i include --------- in the text file to separate the expression it will give me compiler error.

What I have tried:

int main ()
{
   string inputLine;
   ifstream file ("input.txt");
   {
       while (std::getline (file, inputLine))
       {     
           while(!file.eof())
           {
               spaces
               file.ignore(1,'\n');
               inputLine = trim (removeBackspaces (inputLine));
               Parser p (inputLine);
               double value = p.Evaluate ();
               ofstream file;
               file.open("output.txt");
               file <<std::cout << "Result = " << value << std::endl;
               double abc = p ["abc"];
               file<<std::cout << "abc = " << abc << std::endl;
               file<<std::cout<<"----------------------"<<endl;
           }
       } 
       file.close();
    }
}



这是input.txt文件

----

sin(0)

----

cos(0)

----

pi = 3.14 radius = 3 sin(pi / 2)+ pi * radius ^ 2

----

1 + 2

----

10 - 5

----

3 * 4

----

12/4

------------

2 ^ 3


And this is the input.txt file
----
sin(0)
----
cos(0)
----
pi = 3.14 radius = 3 sin( pi / 2 ) + pi * radius ^ 2
----
1 + 2
----
10 - 5
----
3 * 4
----
12 / 4
------------
2 ^ 3

推荐答案

您必须使用调试器来查找错误。对我来说,看起来你应该首先改变第一个while循环头。
You must use the debugger to find your error. For me it looks like you should change the first while loop heads for the start.


首先,你应该将输出文件对象的声明移到while循环之外。您不需要构造它并为从输入文件中读取的每一行打开文件。当你正在阅读输入时,它应该构造一次并保持打开状态。



只有空格的行不清楚。这可能会导致编译错误。



还有一件事,这行也可能导致编译错误:
First, you should move the declaration of the output file object outside the while loop. You don't need to construct it and open the file for every line you read from the input file. It should be constructed once and left open while you are reading input.

The line with just "spaces" is unclear. That will likely cause a compile error.

One more thing, this line will likely cause a compile error also :
double abc = p ["abc"];

它看起来很可疑,但是如果没有看到Parser类的定义就很难知道。

It looks suspicious but it is hard to know without seeing the definition of the Parser class.


这篇关于用C ++读取输入文本文件中的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆