-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.

3
  • You already have the line in a variable. What exactly is your problem? Dec 22, 2013 at 20:03
  • I'd use cerr for error output rather than cout. And I'd mention the name of the file in the error message, but perhaps that's just me.
    – Mr Lister
    Dec 22, 2013 at 20:10
  • Search StackOverflow for "reading lines from file". Dec 22, 2013 at 20:12

3 Answers 3

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.

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>.

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.