0

I have a txt file that contains individual characters line by line. I am kind of confused as to how to read that line by line when the getline function takes in string?

Also would it be possible to store char in a vector? Or would it still work if I stored those individual characters as strings?

A. R
  • 1
  • 2
    There is an overloaded `operator>>` for `ifstream` for `char`, have you tried that? – mediocrevegetable1 Apr 06 '21 at 03:45
  • See [this C++ reference](https://en.cppreference.com/w/cpp) and spend a few days reading a [good book on programming in C++](https://www.stroustrup.com/programming.html). Take inspiration from existing open source C++ software like [FLTK](http://fltk.org/), [RefPerSys](http://refpersys.org/), [fish](https://fishshell.com/). Read also the documentation of your C++ compiler (e.g. [GCC](http://gcc.gnu.org/) to be inked as `g++ -Wall -Wextra -g`) and debugger (e.g. [GDB](https://www.gnu.org/software/gdb/)...) – Basile Starynkevitch Apr 06 '21 at 04:04
  • 2
    Be aware that **StackOverflow is not a do-my-homework website** – Basile Starynkevitch Apr 06 '21 at 04:07

1 Answers1

-3

code show as below:

vector<char> res;
int count = 0;

ifstream fin;
fin.open("***.txt");
string str;
while (!fin.eof())
{
   getline(fin, str);
   res[count++] = str;
}
fin.close();
JeffZhe
  • 11
  • 1
  • 2
    [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) Also, this is needlessly complicated, since you can easily do `fin >> std::noskipws/std::skipws >> yourCharVariable` and then push that to a vector. *Also*, you don't make `count` 0 after each time the loop runs, which might be an issue. – mediocrevegetable1 Apr 06 '21 at 04:03
  • Actually, I'm not sure if this is right at all. How do you index a vector when it is empty? and OP specifically asked to do this `char` by `char` instead of a whole line, which this does not do. – mediocrevegetable1 Apr 06 '21 at 04:06
  • 1
    `res[count++] = str;` accesses the vector out of bounds. `push_back` is the correct method. No need for `count` then since the size of the vector is available. – Retired Ninja Apr 06 '21 at 04:06