繁体   English   中英

C ++如何从文件中读取字符串到带有文件的std :: string变量中是FILE的指针

[英]C++ How to read string from file into std::string variable with file is FILE's pointer

我想从文件输入中读取字符串到std::string变量中。
我声明一个FILE指针来打开文件:

FILE *f = fopen("IN.txt","r");

然后,我使用fscanf()函数进行了阅读:

std::string tempStr;
fscanf(f,"%s",tempStr); //Compile Error
//fscanf(f,"%s",&tempStr);//Runtime Error

因此,我有2个问题:
1.是否可以解决上述问题(仍然使用FILE *ffscanf()函数)?
2.我是一名C程序员,不熟悉C ++。 如何用不同的方式解决这个问题?

这是我的代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int n;
    string cities[100];
    FILE * f = fopen("IN.txt", "r");
    fscanf(f,"%d",&n);
    for (int i=0; i<n;i++)
    {
        string tempStr;
        fscanf(f,"%s",tempStr);
        cities[i] = tempStr;
    }
    return 0;
}

和输入文件(第一行是行号):

8
Vancouver
Yellowknife
Edmonton
Calgary
Winnipeg
Toronto
Montreal
Halifax

如果您想直接读入std::string ,则可以使用FILE*但不能使用fscanf() :执行此操作的方法是创建一个流缓冲区,将FILE*呈现为可以由std::istream

#include <iostream>
#include <stdio.h>
class cfilebuf
    : public std::streambuf {
    FILE* file;
    char  c;
    int underflow() {
        int value = fgetc(this->file);
        if (value != EOF) {
            c = value;
            this->setg(&c, &c, &c + 1);
            return c;
        }
        return std::char_traits<char>::eof();
    }
public:
    cfilebuf(FILE* file): file(file) {}
    // to own or not to own? ~cfilebuf() { fclose(this->file; }
};

int main() {
    cfilebuf     sbuf(stdin);
    std::istream in(&sbuf);
    std::string  s;
    if (in >> s) {
         std::cout << "read '" << s << "'\n";
    }
}

请注意,此流缓冲区适合于您在FILE*std::istream*之间不断切换的设置。 如果您合理地只在FILE*使用std::istream接口,则您希望创建一个读取整个缓冲区的流缓冲区:这将大大提高效率。 另外,您可能希望将流和流缓冲区的构建包打包为一个对象:

class icfilestream
    : private virtual cfilebuf
    , public std::istream {
public:
    icfilestream(FILE* file)
        : cfilebuf(file)
        , std::ios(static_cast<std::streambuf*>(this))
        , std::istream(static_cast<std::streambuf*>(this)) {
    }
};
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int n;
    string cities[100];
    ifstream f("IN.txt");
    f >> n;
    for (int i=0; i<n;i++)
    {
        f >> cities[i];
    }
    return 0;
}

更好的是,将std::vector<string>用于cities (此修改留给读者练习)。

您应该使用流类和std::getline或直接将其读入字符串。 但是,如果您确实需要,可以执行以下操作:

fscanf(f,"%s",tempStr); // tempStr is declared as char tempStr[N]
cities[i] = std::string(tempStr); // convert to a string

请注意,最初是在char缓冲区(超级不安全的btw)中读取的,然后将其转换为std::string 但我认为只要简单地做一下就没有理由使用此代码

fin >> cities[i] 

在一个循环中, finstd::ifstream

暂无
暂无

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

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