c++ - 在文本文件中逐行向前移动 (c++)

标签 c++

我一直在研究一个旨在从文本文件的多行中读取数据的程序。我对第一行没问题,但我不确定如何转到第 2、3 行等。

文件的内容和长度没有设置,但内容可能是这样的:

1.0 1.0 C
1.0 1.0 V
1.0 1.0 S
1.0 1.0 D
1010.0 250.0 C

999

这是我的程序(到目前为止);

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;

int main()
{
    double radius;
    double height;
    char letter[1];

    char Exercise4[80] = "Exercise4.txt";
    ifstream infile;
    infile.open (Exercise4);
    infile >> radius >> height >> letter;

    while (radius != 999) {

    cout << endl << endl;
    double Pi;
    Pi = 3.141592;
    cout << setprecision(2) << fixed;

    //math & calculations
    double Circ;
    Circ = radius*2*Pi;
    double Surf;
    Surf = (2*Pi*radius*radius)+(2*Pi*radius*height);
    double Vol;
    Vol = Pi*radius*radius*height;

        if (strcmp(letter, "C") == 0) {
            cout << "Circumfrence: " << Circ << endl;
        }
        else if (strcmp(letter, "S") == 0) {
            cout << "Surface Area: " << Surf << endl;
        }
        else if (strcmp(letter, "V") == 0) {
            cout << "Volume: " << Vol << endl;
        }
        else {
            cout << "Invalid calculation type." << endl;
        }

        cout << letter;
    }
}

任何关于如何向前推进的信息都将不胜感激。

很抱歉,如果这个问题已经发布(看起来应该已经发布),但我还没有看到它发布在任何地方。

我是 C++ 的新手,所以如果你太技术化,我可能无法理解你所说的一切。

最佳答案

我建议这样做:

...
infile.open (Exercise4);

while((infile >> radius) && radius!=999 && (infile >> height >> letter)) { 
    ...
}

这将在遇到半径 999 或到达文件末尾时停止读取,无论先发生什么。

关于c++ - 在文本文件中逐行向前移动 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36072074/

相关文章:

c++ - 我需要清理非指针数据成员吗?

c++ - 局部变量初始化: are these methods different semantically?

c++在类似结构的数组中仅给出字符串的一部分时查找字符串

c++ - QT中的动态内存释放

c++ - 将 Qt qmake Makefile 与自定义 Makefile 混合

c++ - 如果函数抛出的异常可能未被捕获,如何销毁局部变量?

c++ - 字符数组输出不正确

c++ - 相同版本的 clang 在不同操作系统上给出不同的结果

c++ - 您可以在字符串文字中放置中断吗?

c++ - 枚举已安装产品的升级代码?