C++如何从文件中设置字符串变量

C++ How to set a string variable from a file?

本文关键字:设置 字符串 变量 文件 C++      更新时间:2023-10-16

我想知道如何在程序中读取WHOLE txt文件并将其内容设置为1个字符串。我已经声明了我的字符串:

const string SLOWA[ILOSC_WYRAZOW][ILOSC_POL] = 
{
    {"kalkulator", "Liczysz na tym."},
    {"monitor", "pokazuje obraz."},
    {"kupa", "robisz to w toalecie"}
};

我不想把它放在程序中,而是想把这个字符串的内部放在.txt文件中,读取整个内容并将其设置为我的字符串。有可能吗?

试试这个:

#include<iostream>
#include<fstream.h>
using namespace std;
int main(){
   ifstream file("d:\data.txt");
   string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
   cout<<content;
   getchar();
   return 0;
}

现在content变量包含文件中的全部数据。

文件data.txt包含:

this is file handling
and this is contents.

输出:

this is file handling
and this is contents.

以下内容将起作用:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    string line;
    string mystring;
    ifstream myfile ("example.txt");   // Need to be in the directory where this program resides.
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )  // Get one line at a time.
        {
            mystring += line + 'n';    // 'n' at the end because streams read line by line
        }
        myfile.close();                   //Close the file
    }
    else
        cout << "Unable to open file";
    cout<<mystring<<endl;
    return 0;
}

但看看流是如何工作的:

http://courses.cs.vt.edu/cs1044/Notes/C04.IO.pdf

http://www.cplusplus.com/reference/iolibrary/