-1

I'm trying to read in data from a text file. How would I do that from C++. Do I have use the input mode?

open(fileName,ios::in)

If so, then how to I read in data, in string form?

Thanks

  • You should probably use [fstream](https://en.cppreference.com/w/cpp/io/basic_fstream) – Thomas Sablik Dec 05 '20 at 09:51
  • Since this is for a school assignment I guess, is there any sort of support provided by your professor? There should be, I hope. Office hours? A virtual meeting place for the students in that course? I'm afraid that the best way to learn this is to get a book or look at online tutorials, but a lot of tutorial material is of the "blind leading the blind" kind and it's very hard for a novice to tell which is which :( This may be one viable starting point: https://github.com/tuvtran/project-based-learning – Kuba hasn't forgotten Monica Dec 07 '20 at 05:07

1 Answers1

1

This is the easiest way to do this:

#include <fstream>
#include <string>
#include <vector>

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

    std::ifstream myfile("example.txt"); //name of your txt file

    while (std::getline(myfile, str)) { // read txt file line by line into str 
        vec.push_back(str);  //you have to store the data of str
    }

    myfile.close(); // optional, streams are RAII types
                    // and thus close automatically on leaving scope
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313