为什么第一种方式的输出和其他方式不一致?
#include
#include
#include
using namespace std;
void test01()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
}
// 第一种方式
/*char buf[1024] = { 0 };
while (ifs >> buf)
{
cout << buf << endl;
}
ifs.close();*/
// 第二种方式
/*char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
}
ifs.close();*/
// 第三种方式
/*string buf;
while (getline(ifs, buf))
{
cout << buf << endl;
}
ifs.close();*/
// 第四种方式
char c;
while ((c = ifs.get()) != EOF) // EOF = end of file
{
cout << c;
}
ifs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
图1-第一种方式的输出结果
图2-第二种方式的输出结果
图3-第三种方式的输出结果
图4-第四种方式的输出结果
getline是读取一行,遇到换行符则读取结束
而>>是将空格作为分隔符,遇到空格则读取结束