本程序实现了从一个文本文件中读取字符串,边界符号为“:”
- // strfile.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
- //
-
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cstdlib>
- int main()
- {
- // std::cout << "Hello World!\n";
- using namespace std;
- ifstream fin;
- fin.open("tobuy.txt");
- if (fin.is_open() == false)
- {
- cerr << "Can not open file, Bye .\n";
- exit(EXIT_FAILURE);
- }
- string item;
- int count = 0;
- getline(fin,item,':');
- while (fin)//while input is good
- {
- ++count;
- cout << count << ": " << item << endl;
- getline(fin,item,':');
- }
- cout << "Done\n";
- fin.close();
- return 0;
- }
-
-
tobuy.txt 内容如下:
sardines:chocolate ice cream:pop corn:leeks:cttage cheese:olive oil:butter:tofu:
运行结果:
