简体   繁体   中英

How to read a file with spaces in C++?

I started having C++ classes at university last week. At the moment I just know some C language which makes me a little confused when learning C++. I have this exercise that says: "Write and use the fstream library to read a text file. The function should write on the screen each text line read of the file (with spaces)."

I wrote the code below that can write the line but without spaces. I've also heard about getline, but I don't know how to use it, the compiler allways says "no matching function for call to getline".

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

using namespace std;

file_read(){
    ifstream origem;
    origem.open("ficheiro.txt");


    if (!origem) {
        cerr << "Error" << endl;
        return -1;
    }
char outp[100];

while(!origem.eof() ){
    origem >> outp;
    cout << outp;
    }

return 0;
}

For example: If i have in the ficcheiro.txt "My dog has a bone", the programm will write it like "Mydoghasabone"

So with the getline I tried this:

...
    ifstream origem;
    origem.open("ficheiro.txt");


    if (!origem) {
        cerr << "Error" << endl;
        return -1;
}
    char outp[100];

    getline(origem, outp);
    origem >> outp;
    cout << outp;

    return 0;
}

The compiler said:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'

My problem is just to read the file including the spaces!


I'm also having some trouble learning C++, I started learning 'Classes' and using the CMD and I don't even know what I'm learning. Do you know where can I learn C++ in a more understandable way?

Try this

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

using namespace std;

int file_read()
{
    ifstream origem;
    origem.open("ficheiro.txt");


    if (!origem) {
        cerr << "Error" << endl;
        return -1; 
    }
    char outp[100];

   while( origem.getline(outp,100) )
        cout << outp;

return 0;
}

int main()
{
    file_read();
}

The compiler said:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'

if you want to use getline() change outp from char to string like

string outp;

while( getline(origem,outp))
    cout << outp;

Because getline() is for string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM