Omer
Omer

Reputation: 88

Problem with getting text from a .txt file in c++ using fstream

ThisAnd thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:

#include <iostream>
#include <fstream>
using namespace std;


int main(int argc, const char * argv[]) {
    string line;
    string lines[100];
    ifstream myfile ("CodeHere.txt");
    int i = 0;
    if (myfile.is_open())
    {
      while ( getline (myfile,line) )
      {
          lines[0] = line;
          i++;
          
      }
      myfile.close();
    }

    else cout << "Unable to open file";
    
    cout << lines[0];
    
    myfile.close();

    return 0;
}

And the output is: Writing this to a file.Program ended with exit code: 0

But in my CodeHere.txt it has: hello

I tried saving it, but the result didn't change. I'm not sure whats going on. Can anyone help?

Upvotes: 1

Views: 896

Answers (3)

V&#233;limir
V&#233;limir

Reputation: 421

Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.

Upvotes: 1

fjcop
fjcop

Reputation: 61

Try this:

  vector<string> lines;
  if (file.is_open()) {
    // read all lines from the file
    std::string line;
    while (getline(file, line)) {
      lines.emplace_back(line);
    }
    file.close();
  }
  else {
    cout << "Unable to open file";
    return -1;
  }
  cout << "file has " << lines.size() << " lines." << endl;
  for (auto l : lines) {
    cout << l << endl;
  } 

Upvotes: 1

Giogre
Giogre

Reputation: 1504

This should work, using a vector<string> to store the lines read from file

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main(int argc, const char * argv[]) {
    string line;
    vector<string> lines;
    ifstream myfile ("CodeHere.txt");
    int i = 0;
    if (myfile.is_open())
    {
        while ( getline(myfile, line) )
        {
             lines.push_back(line);
             i++;       
        }
        myfile.close();
    }
    else {
        cout << "Unable to open file";
        return -1;
    }

    cout << lines[0] << '\n';

return 0;
}

Upvotes: 1

Related Questions