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

Time:05-07

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;
}

CodePudding user response:

obj.getline() isn't valid. I see in your comments you meant to write obj.get(), so I'll stick with using that.

The main problem is that you are opening and closing the file within your do-while loop, which means that, for each iteration, you will open the file, read a character, then close the file. Each time you open the file, you actually start at the beginning, and thus you will not read until you get to an 'x' character, but basically infinitely.

I didn't test this, but this seems to be what you want (comments added):

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

int main()
{
    std::ifstream obj("test.txt"); // open the file (no need to specify "in")
    if ( !obj ) { // check to see if the file could be opened
        std::cout << "Could not open file\n";
    } else {
        char a;
        while ( obj >> a ) { // while there's still something to read
            if ( a != 'x' ) { // if it's not an 'x' character, print it
                std::cout << a << std::endl;
            } else {
                break; // otherwise, break the loop
            }
        }
        obj.close(); // close the file
    }
    
    return 0;
}

CodePudding user response:

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
  • Related