[英]How to read a value from a text file and store that value into a temporary variable?
[英]How to store the text from a .txt file into a variable
我想將.txt
文件中的文本保存為 C++ 上的char
變量。 我試過了:
char fileData;
fstream myFile;
myFile.open("file name");
fileData = myFile;
myFile.close();
cout<<fileData;
但這是錯誤的,我收到一個錯誤, invalid user-defined conversion from 'std::fstream {aka std::basic_fstream<char>}' to 'int' [-fpermissive]
誰能幫我?
打開文件后,您還需要讀取它以獲取其在變量中的數據。
另外,我注意到您沒有指定是讀取文件還是寫入文件。
您可以通過以下方式獲取文件的內容:
myfile>>fileData;
您可以分別通過 ios::in 或 ios::out 指定文件是以讀模式還是以寫模式打開。
myfile.open ("demo.txt", ios::out| ios::in );
您還可以使用"ifstream"從文件內部獲取第一個(或單個現有)字符,例如:
myFile.open("file name");
⚠️ 如果您不是在尋找寫入文件。
(使用示例):
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileData;
ifstream myFile;
myFile.open("file name");
myFile.read(&fileData,1);
myFile.close();
cout<<fileData;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.