導航:首頁 > 文件教程 > 讀取文件string

讀取文件string

發布時間:2025-02-25 12:51:47

Ⅰ C++中如何讀取文件內容

兩種讀取方法,一種是按行讀取,一種是按單詞讀取,具體如下:

1、按照行讀取

string filename = "C:\Users\asusa\Desktop\藍橋\rd.txt";

fstream fin;

fin.open(filename.c_str(), ios::in);

(此處空格一行)

vector<string> v;

string tmp;

(此處空格一行)

while (getline(fin, tmp))

{

v.push_back(tmp);

}

(此處空格一行)

for (auto x : v)

cout << x << endl;

2、按照單詞讀取

string filename = "C:\Users\asusa\Desktop\藍橋\rd.txt";

fstream fin;

fin.open(filename.c_str(), ios::in);

(此處空格一行)

vector<string> v;

string tmp;

(此處空格一行)

while (fin >> tmp)

{

v.push_back(tmp);

}

(此處空格一行)

for (auto x : v)

cout << x << endl;

(1)讀取文件string擴展閱讀:

有讀取就有寫入,下面是寫入的方法

//向文件寫五次hello。

fstream out;

out.open("C:\Users\asusa\Desktop\藍橋\wr.txt", ios::out);

(此處空格一行)

if (!out.is_open())

{

cout << "讀取文件失敗" << endl;

}

string s = "hello";

(此處空格一行)

for (int i = 0; i < 5; ++i)

{

out << s.c_str() << endl;

}

out.close();

java讀取text文件為String,如何實現

/**
* 主要是輸入流的使用,最常用的寫法
* @param filePath
* @return
*/
public static String read(String filePath)
{
// 讀取txt內容為字元串
StringBuffer txtContent = new StringBuffer();
// 每次讀取的byte數
byte[] b = new byte[8 * 1024];
InputStream in = null;
try
{
// 文件輸入流
in = new FileInputStream(filePath);
while (in.read(b) != -1)
{
// 字元串拼接
txtContent.append(new String(b));
}
// 關閉流
in.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return txtContent.toString();
}

Ⅲ 讀取xml文件獲取String字元串為亂碼,怎麼解決

1首先打開XML文件
2發現文件中的中文是亂碼狀態,找到開頭的這段代碼
<?xml version="1.0" encoding="ISO-8859-1"?>

3將代碼修改為<?xml version="1.0" encoding="gb2312" ?>後保存退出,再打開文件

4你會發現之前的亂碼已經全部是中文了,可以想如何修改就怎麼修改了
5有些文件不支持中文字元,編輯完成後將編碼修改成原來的再保存,防止出錯。

閱讀全文

與讀取文件string相關的資料

熱點內容
上海國衡網站有什麼用 瀏覽:29
掃描文件如何全選 瀏覽:363
directx一鍵修復工具 瀏覽:620
如何恢復谷歌同步中刪除的文件夾 瀏覽:215
安卓51轉換為系統應用 瀏覽:789
哪裡看雙11數據 瀏覽:783
文件變成exe如何恢復 瀏覽:49
為什麼逆戰會缺少文件 瀏覽:180
蘋果4s版本怎麼更新 瀏覽:418
手機網路共享密碼錯誤 瀏覽:535
電腦清理沒用的文件 瀏覽:211
資料庫關系運算符號 瀏覽:968
如何把微雲網路文件 瀏覽:239
win10怎麼防止文件被刪除 瀏覽:82
香港有蘋果翻新機嗎 瀏覽:15
c讀取文件的行數 瀏覽:59
重慶少兒編程哪裡好 瀏覽:568
nes游戲在哪個文件夾里 瀏覽:643
ps怎麼剪貼到別的文件 瀏覽:352
如何導出文件 瀏覽:595

友情鏈接