读取文件内容fstream.eof()和peek()

xiaoxiao2025-04-19  10

a.txt

你好 hello 上午好 中午好 下午好 晚上好 再见

 

peek.cpp

#include <iostream> #include <cstdio> #include <fstream> #include <string.h> #include <vector> using namespace std; int main() { vector<string> vec; char buff[256]; fstream file; file.open("a.txt",ios::binary| ios::in); if(file.is_open()) { //while(!file.eof()) while(file.peek()!=EOF) { file.getline(buff,sizeof(buff)); int len = strlen(buff); string str = buff; cout << "buff = "<< buff<< endl; vec.push_back(str); } int a = vec.size(); cout << "vec.size=" << a << endl; } else { cout << "open failed" << endl; return 0; } }

peek.cpp输出

buff = 你好 buff = hello buff = 上午好 buff = 中午好 buff = 下午好 buff = 晚上好 buff = 再见 vec.size=7

如果是用

while(!file.eof())

则输入如下:

buff = 你好 buff = hello buff = 上午好 buff = 中午好 buff = 下午好 buff = 晚上好 buff = 再见 buff = vec.size=8

 

 

转载请注明原文地址: https://www.6miu.com/read-5028629.html

最新回复(0)