2014-10-07 24 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/