文件读取C++包括空格键
File Reading in C++ including spacebars
我试图打开文件并使用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 不好?
欲了解更多信息,我建议习惯这个网站
相关文章:
- 文件读取C++包括空格键
- C++ - 如何将空格键转换为短划线以进行cmd输入
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- VideoFrames只有在按下esc,空格键或回车键时才会出现OpenCV c ++
- 回文,不包括特殊字符和空格
- 通过按空格键结束键盘输入数据,而不是输入键 c/c++
- 从键盘获取C++中的任何键,包括控制等键
- 如何继续输入,直到用户按下空格键
- 将文本写入文件,包括空格
- 避免使用 wxButton 的空格键和回车键
- 如何仅测试字符数组的字母(包括空格)
- 发送空格键按下游戏bhop破解
- 如何捕获 CTRL + 空格键 + 空格键按下
- 如何检测空格键
- Visual Studio MFC CListCtrl 复选框 - 空格键
- 在hashmap中搜索,其中键可以是单个字符串或空格分隔的字符串
- Qt主窗口手柄空格键按下
- 射击按钮在游戏中触发多次而不是一次时,按空格键
- 在cin中使用空格键和回车键输入值的区别
- 计算不带空格键的字符串中的字母