OJFord
OJFord

Reputation: 11130

Read text file char by char

I've tried code from several other questions/tutorials, always getting whitespace or nothing back.

in.txt:

a
z

main.cpp:

ifstream in (argv[1]);
in.open(argv[1]);
if (!in.is_open()) exit(EXIT_FAILURE);
char c;
in >> c;
cout << c;

Doesn't pass anything back to cout, as though there is no character. What am I doing wrong?

Upvotes: 1

Views: 6644

Answers (2)

KeyC0de
KeyC0de

Reputation: 5267

To read a file char-by-char, while respecting input text formatting, you can use the following:

if (in.is_open())
    char c;
    while (in.get(c)) {
        std::cout << c;
    }
}

where in is an input stream of type std::ifstream. You can open such a file, like so: std::ifstream in('myFile.txt');

This is an unbeffered read. Buffered reads are typically preferred (eg. line-by-line).

Upvotes: 1

Marco A.
Marco A.

Reputation: 43662

You're trying to re-open an already-opened file without freeing the resource before thus putting it into an unconsistent state

http://www.cplusplus.com/reference/fstream/ifstream/ifstream/

#include<fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char*argv[]){

  std::ifstream in ("mytext.txt");
  char c;
  in >> c;
  cout << c;

  in.open("mytext.txt");

  if(!in.good())
    cout << "unconsistent state!";

  return 0;

}

If the object already has a file associated (open), the function fails.

Upvotes: 3

Related Questions