繁体   English   中英

如何在C++中读取带有空格的文件?

[英]How to read a file with spaces in C++?

我上周开始在大学上 C++ 课程。 目前我只知道一些 C 语言,这让我在学习 C++ 时有点困惑。 我有一个练习说:“编写并使用fstream库读取文本文件。该函数应该在屏幕上写入文件的每个文本行读取(带空格)。”

我写了下面的代码,可以写行但没有空格。 我也听说过 getline,但我不知道如何使用它,编译器总是说“没有匹配的函数调用 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;
}

例如:如果我在ficcheiro.txt “My dog has a bone”,程序会写成“Mydoghasabone”

所以用 getline 我试过这个:

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

编译器说:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'

我的问题只是读取包含空格的文件!


我在学习 C++ 时也遇到了一些麻烦,我开始学习“类”并使用 CMD,我什至不知道我在学习什么。 你知道我在哪里可以以更容易理解的方式学习 C++ 吗?

尝试这个

#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();
}

编译器说:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'

如果您想使用 getline() 将输出从字符更改为字符串,例如

string outp;

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

因为 getline() 是用于string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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