#include<iostream>
#include <fstream>
#include <string>
using namespace std;
void CreateTXT1()//创建文本
{
fstream b("data.txt", ios::out);
b << "文字1" << "\t";
b << "文字2" << endl;
b << "文字3";
b.close();
}
void CreateTXT2()//创建文本
{
fstream b("data.txt", ios::out);
b << "文字1" << "\t";
b << "文字2" << endl;
b << "文字3" << endl;//与CreateTXT1相比,多加入一个endl
b.close();
}
void test1()//使用getline()
{
ifstream ifs;
ifs.open("data.txt", ios::in);
string A;
int m = 0;//while循环运行次数
if (!ifs.is_open())
{
cout << "打开失败" << endl;
}
while (getline(ifs, A)) //getline读文件
{
cout << A << endl;
cout << "“test1”中while函数运行" << endl;
m++;
}
cout << "while循环运行次数为" << m << endl;
cout << "string A此时的内容为:" << A << endl;//打印string A
ifs.close();
}
void test2()//使用>>
{
ifstream ifs;
ifs.open("data.txt", ios::in);
string A;
int m = 0;//while循环运行次数
if (!ifs.is_open())
{
cout << "打开失败" << endl;
}
while (ifs >> A)
{
cout << A << endl;
cout << "“test2”中while函数运行" << endl;
m++;
}
cout << "while循环运行次数为" << m << endl;
cout << "string A此时的内容为:" << A << endl;//打印string A
ifs.close();
}
int main() {
//使用getline的函数
CreateTXT1();
test1();
CreateTXT2();
test1();
//使用>>的函数
CreateTXT1();
test2();
CreateTXT1();
test2();
system("pause");
return 0;
}
运行结果为
发现在使用>>输入文件时,结果是相同的,都进行3次while循环,打印出相同的内容,最后string A都为“文字3”。
在使用getline()时,都进行了2次while循环,打印出相同的内容,但是在最后sting A的内容不同。在输入以endl为结尾的CreateTXT2后,string A的内容变为空。
疑问:
①:为什么两次test1中,最后string A的内容会不同,以及为什么while循环中打印出来的内容却还是相同的呢?
②:为什么在两次test2中,两次结果相等,而没有产生和问题①同样的情况?
③:新建一个函数,来检测输入流的位置
void CreateTXT1()//创建文本
{
fstream b("data.txt", ios::out);
b << "文字1" << "\t";
b << "文字2" << endl;
b << "文字3";
b.close();
}
void test3()//检测输入流
{
ifstream ifs;
ifs.open("data.txt", ios::in);
string A;
getline(ifs, A);
cout << ifs.eof() << endl;
getline(ifs, A);
cout << ifs.eof() << endl;
}
int main() {
CreateTXT1();
test3();
system("pause");
return 0;
}
得到的结果:第一个ifs.eof()=0,第二个ifs.eof()=1
那么,在第一次test1中,为什么能进行两次while循环?当getline()读取到eof,不是应该返回一个否值来退出while循环吗?也就是说读取到第二行后,为什么没有直接退出while循环,而是又运行了一次呢?