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

时间:2014-10-07 13:45:16

标签: c++ string fstream

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

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

我希望在.txt文件中包含此字符串的内部并读取整个内容并将其设置为我的字符串,而不是在程序中使用它。有可能吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

#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.

答案 1 :(得分:0)

以下内容可行:

#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/