-2

contents of file.txt

a
b
c

a
b
c1 x c2
d

a, b, c, c1, c2, d are all some values.

My function

void Menu::readFile() {
    string line;
    ifstream myfile ("file.txt");

    if (myfile.is_open()) {
        while (getline (myfile, line)) {
            cout << line << "\n";
        }

        myfile.close();
    } else cout << "Unable to open file"; 
}

This is just returning the contents of the file, how can I read the file and parse each line into a variable. Each line break separates the objects.

Peter Nimroot
  • 545
  • 5
  • 14
Eric Goncalves
  • 5,253
  • 4
  • 35
  • 59

3 Answers3

1
void Menu::readFile() {
    string line;
    vector <string> lines;
    ifstream myfile ("file.txt");

    if (myfile.is_open()) {
        while (getline (myfile, line)) {
          cout << line << "\n";
          lines.push_back(line);
        }

        myfile.close();
    } else { 
       cout << "Unable to open file"; 
    }
}

the variable lines will have all the lines.

SamFisher83
  • 3,937
  • 9
  • 39
  • 52
0

This function is not returning anything. It is declared and so it can not return any value. What you have is already parsing the lines one by one. Now instead of printing them on this line:

cout << line << "\n";

You should store them in some container e.g. std::vector<std::string>.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

Best to use a list or vector. Here is an example using algorithms and iterators:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

int main() {
  std::vector<std::string> vals;

  std::copy(
    std::istream_iterator<std::string>(std::cin),
    std::istream_iterator<std::string>(),
    std::back_inserter(vals)
  );

  // Print them out, appending a newline to each word

  std::copy(
    vals.begin(),
    vals.end(),
    std::ostream_iterator<std::string>(std::cout, "\n")
  );
}

You can substitute any std::istream object initialize to the std::istream_iterator; in particular your myfile variable. The default constructor (empty parens) constructs an end-of-stream iterator.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112