如何从文件中读取字符串到string对象

来源:互联网 发布:js sleep函数 编辑:程序博客网 时间:2024/05/16 15:36
//strfile.cpp -- read stings from a file#include <iostream>#include <fstream>#include <string>#include <cstdlib>int main(){using namespace std;ifstream fin;                     //定义输入文件流对象fin fin.open("tobuy.txt");            //用fin对象打开文件“tobuy.txt”if ( fin.is_open() == false )     //打开失败则返回错误{cerr << "Can't open file. Bye.\n";exit(EXIT_FAILURE);}string item;                       //定义字符串对象int count = 0;getline(fin, item, ':');          //从fin对象中向item对象中读取字符串,遇到“:”字符则完成一次读取while(fin)                        //只要没读到文件尾,则循环读取并输出读取内容{++count;cout << count << ": " << item << endl;getline(fin, item, ':');}cout << "Done\n";fin.close();                      //关闭文件cin.get();                        //此行作用是为了让程序运行窗口能持续显示,以便观察运行效果。return 0;}

运行效果如图:


注:tobuy.txt 的内容为:


        需要注意的一点是,通过测试,可以得知:当冒号 “ :”指定为分界字符后,换行符将被视为常规字符,因此文件第一行末尾的换行符将成为包含“cottage cheese”的字符串中的第一个字符。同样,第二行末尾的换行符是第9个输入字符串中唯一的内容。




0 0
原创粉丝点击