本程序实现了从一个文本文件中读取字符串,边界符号为“:”
// 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:
运行结果:

该程序演示了如何使用C++从名为'tobuy.txt'的文本文件中读取以':'分隔的字符串。它首先打开文件,然后逐行读取直到文件结束,每次遇到':'时截断字符串并输出计数和提取的项。示例文件包含一系列购物清单项目。

被折叠的 条评论
为什么被折叠?



