Home > Net >  I have been trying to read from a .txt using C but nothing gets outputted
I have been trying to read from a .txt using C but nothing gets outputted

Time:12-07

I need help reading from a .txt file on C . The code I wrote is supposed to take in command line arguments, one of which is the name of the file, read the file, store its contents in a string and print the content of that string as output. I am using the Ubuntu WSL 2 terminal. And whenever I run the code, it takes in the commands using the arguments and opens the file without issues but doesn't print anything out. I don't know what to do.

#include <bits/stdc  .h>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char** argv){
    string filename = argv[1];

    cout << filename << endl; 

    string myText;
    ifstream myReadFile;
    
    myReadFile.open(filename);
    

    while(getline (myReadFile, myText)){
        cout << myText; 
    }

    cout << "Why is my code not doing what it is meant to?" << endl;
    myReadFile.close();
    return 0;
}

That is what was in the file that was supposed to be printed out using cout.

The man in the mirror does not exist. 

CodePudding user response:

i find solution here https://www.tutorialspoint.com/how-to-read-a-text-file-with-cplusplus , it may help you. This is the standard reading method .txt files in c

CodePudding user response:

The idiomatic way to read lines from a stream is this:

ifstream filein(filename);

for (string line; getline(filein, line); ) 
{
    cout << line << endl;
}

Notes:

  1. No close(). C takes care of resource management for you when used idiomatically.

  2. Use the free getline, not the stream member function.

  • Related