2014-10-07 25 views
-1

我想知道我怎么能读取整个txt文件,并设置它作为我的程序1个字符串内容。我宣布我的字符串:C++如何从文件设置字符串变量?

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

而是在节目中有它,我想有这个字符串的.txt文件的内部和阅读的全部内容,并把它设置为我的字符串。可能吗?

+0

这是字符串的二维数组,而不是字符串。你想从文件中读取1个字符串还是要填充这个数组? – interjay 2014-10-07 13:48:36

+1

我从来没有见过像你这样的字符串 – gkovacs90 2014-10-07 13:48:37

+0

是的。这是一个字符串的2D。搜索一下。 – gsamaras 2014-10-07 13:48:42

回答

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. 
+0

你的方法和字符串内容有什么区别;文件>>内容;' – 2014-10-07 14:16:18

+0

我没有得到你 – Rustam 2014-10-07 14:17:40

+0

什么'字符串内容((标准:: istreambuf_iterator (文件))的std :: istreambuf_iterator ())'做。将整个文件加载到字符串中?它是否包含空格? – 2014-10-07 14:57:11

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/