如何从文件写入字符串

How to write from file to string

我是 C++ 的新手,我无法理解如何从文件中导入文本。我有一个从中输入的 .txt 文件,我想将该文件中的所有文本放入一个字符串中。要阅读文本文件,我使用以下代码:

ifstream textFile("information.txt");

其中只是读取一个文本文件名信息。我制作了一个名为文本的字符串并将其初始化为“”。我的问题是以下代码,我试图用它来将 .txt 文件中的文本放到字符串中:

while (textFile >> text)
    text += textFile;

我显然做错了什么,虽然我不确定它是什么。

while (textFile >> text) text += textFile;

您正在尝试将文件添加到字符串中,我认为这是编译器错误。

如果您想按照自己的方式进行操作,则需要两个字符串,例如

string text;
string tmp;
while(textFile >> tmp) text += tmp;

请注意,这可能会省略空格,因此您可能需要手动重新添加它们。

while (textFile >> text) 不会保留空格。如果你想保留字符串中的空格,你应该使用其他函数,如 textFile.get()

示例:

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



int main(){  
    std::ifstream textFile("information.txt");
    std::string text,tmp; 
    while(true){
        tmp=textFile.get();
        if(textFile.eof()){ break;}
        text+=tmp;
        }
        std::cout<<text;

return(0);}