文件读取C++包括空格键

File Reading in C++ including spacebars

本文关键字:空格键 包括 C++ 读取 文件      更新时间:2023-10-16

我试图打开文件并使用C++读取它。代码如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void open_file(string filename)
{
string data;
ifstream file;
file.open(filename);
file >> data;
cout << data;
}
int main()
{
open_file("file.txt");
}

但是当文件中的字符为空格时,输出结束。 文件:

This message will be printed

输出:

This

有人可以帮助我吗?

是的。这是提取器的标准行为。

您应该使用std::getline来阅读整行。这将读取到一行的末尾(用""表示(。

所以:

std::getline(file, data);

请参阅此处了解更多信息。

usestd::getline((

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void open_file(string filename)
{
string data;
ifstream file;
file.open(filename);
getline(file,data);      //This will read until the end of a line
cout << data;
}
int main()
{
open_file("file.txt");
}

不要使用使用命名空间 std,请参阅此处以获取更多信息为什么使用命名空间 std 不好?

欲了解更多信息,我建议习惯这个网站