1

I have been working on a program designed to read data from several lines of a text file. I have had no problem with the first line but I am not sure how to move onto line 2, 3, etc.

The contents and length of the file are not set, but the contents could be something like this:

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

This is my program (so far);

#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;
    }
}

Any info on how to move forward by a line would be deeply appreciated.

I am sorry if this question has already been posted (it seems like it would have been), but I have not seen it posted anywhere.

I am relatively new to C++, so I might not understand everything you say if you get too technical.

Martin Evans
  • 37,882
  • 15
  • 62
  • 83
Eli Lewis
  • 13
  • 3
  • Possible duplicate of [Read file line by line](http://stackoverflow.com/questions/7868936/read-file-line-by-line) – ahoffner Mar 17 '16 at 21:49

3 Answers3

1

Something like

while(infile >> radius >> height >> letter) { 
     // process, radius height and letter
}

should warp you where you want to get.

The input line

999

will stop that loop.

πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
1

I'd suggest to do:

...
infile.open (Exercise4);

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

This will stop the reading either when encountering a radius of 999 or reaching end of file, whatever occurs first.

Christophe
  • 54,708
  • 5
  • 52
  • 107
0

I will suggest you to use getline;

std::ifstream fin("myFile.txt");

for (std::string line; std::getline(fin, line); )
{
    std::cout << line << std::endl;
}

This is what you ask exactly but not suitable for your sample program. Because in this case you need to parse each line to get your variable. However if you are trying to learn how to do such things, I suggest you to learn getline.

Semih Ozmen
  • 560
  • 5
  • 19