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

熱點內容
地圖特效代碼 瀏覽:192
去除思科配置文件中的號 瀏覽:196
運行的16位程序太多 瀏覽:1
蘋果mac用什麼軟體好學編程 瀏覽:681
ai中線段怎麼添加寬度配置文件 瀏覽:956
lol文件怎麼找不到game 瀏覽:142
aecc視頻教程 瀏覽:983
linux怎麼查看資料庫用戶名 瀏覽:182
cefs文件系統 瀏覽:404
學平面設計個編程哪個好 瀏覽:701
如何把編程文件轉為hex 瀏覽:80
清除蘋果地圖來自地址 瀏覽:233
已經打開的文件如何清理 瀏覽:685
視頻網站有什麼用 瀏覽:70
多個表格文件怎樣壓縮文件 瀏覽:729
cad文件大很卡如何解決 瀏覽:633
將java程序打包成apk 瀏覽:277
2021唱吧文件找不到了 瀏覽:463
華為p9手機文件管理 瀏覽:284
固定在工具欄的文件夾怎麼查找路徑 瀏覽:667

友情鏈接