C++读txt

先上代码

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cassert>
 4 #include <string>
 5 #include <vector>
 6 
 7 using namespace std;
 8 
 9 vector<string> split(string str)
10 {
11     
12     vector<string> result;
13     string temp("");
14     
15     for (size_t i = 0; i < str.size(); i++)
16     {
17         if (str[i] == '$' )
18         {
19             result.push_back(temp);
20             temp = "";
21         }
22         else
23         {
24             temp += str[i];
25         }
26     }
27     return result;
28 }
29 
30 
31 //1 逐行读取
32 void readTxt(string file)
33 {
34     ifstream infile;
35     infile.open(file.data());   //将文件流对象与文件连接起来 
36     assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 
37 
38     string s;
39     while (getline(infile, s))
40     {
41         cout << s << endl;
42         vector<string> result = split(s);
43         for (size_t i = 0; i < result.size(); i++)
44         {
45             cout << result[i] << "  ";
46         }
47         cout << endl;
48     }
49     infile.close();             //关闭文件输入流 
50 }
51 
52 
53 int main() 
54 {
55     readTxt("merge.txt");
56     system("pause");
57     return 0;
58 }

 关于文本文件编码格式问题,可以参考下面的博客:

https://www.cnblogs.com/yiluyaoyao/articles/5026166.html

posted @ 2020-05-07 17:43  巨鹿王十二  阅读(161)  评论(0编辑  收藏  举报