導航:首頁 > 文件教程 > 讀取文件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相關的資料

熱點內容
ps3文件分割視頻 瀏覽:280
微信圖片一鍵轉發軟體 瀏覽:331
如何判斷s200plc編程電纜 瀏覽:691
太原編程培訓班哪個好 瀏覽:171
樹葉吹奏教程 瀏覽:6
社交app帶來了哪些社會問題 瀏覽:394
如何安裝愛寶8800數據採集器 瀏覽:712
文件保存了怎麼找不到了 瀏覽:476
彩票網站怎麼辨真假 瀏覽:840
pr找不到該文件 瀏覽:963
java移除panel 瀏覽:354
jsp填充jsp 瀏覽:166
海關外貿大數據在哪裡查 瀏覽:381
思特奇java筆試題 瀏覽:121
葫蘆俠在手機中的文件名 瀏覽:813
plc編程應該怎麼收錢 瀏覽:584
c語言中源文件由什麼組成 瀏覽:890
linuxhttpdphp配置文件 瀏覽:607
拆單數據要怎麼保存 瀏覽:17
mac電腦怎樣壓縮文件到100m 瀏覽:645

友情鏈接