Search code examples
c++filetext-filesfstreamiostream

How to get characters from a file and display on console?


I got this code from notes about file handling. From what I understand about this code, I want to get characters till x is reached in the file using this code. Why am I getting only the first character? If this code is incorrect, how should I alter the code to get characters till x is reached? Please help me understand this.<

#include<iostream>
#include<fstream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
    char a = '-';
    do
    {

        ifstream obj("test.txt", ifstream::in);// in would mean import from txt to ram
       // cout << obj << endl;
        if (obj.good() && a != obj.peek())
        {
            a = obj.getline();
            cout << a << endl;
        }
        obj.close();
    } while (a != 'x');
    
    return 0;
}

Solution

  • a is a character and std::getline() returns an istream. Isn't there something wrong here? You cannot assign an istream to a char, so the code doesn't even compile.

    You can simplify your code into this working example:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    int main()
    {
        ifstream obj("test.txt", ifstream::in);
    
        if (obj.good())
        {
            std::string line;
            while (std::getline(obj, line))
            {
                for (auto& i : line)
                {
                    if (i == 'x') return 0;
                    cout << i << endl;
                }
            }
        }
        obj.close();
        return 0;
    }
    

    test.txt:

    This is
    a
    test fixle
    

    Output:

    T
    h
    i
    s
    
    i
    s
    a
    t
    e
    s
    t
    
    f
    i