遇到getline、fstream、作用域不一致的问题
Stumbling across getline, fstream, scope inconsistency
我正在阅读std::getline(),但我不知道我做错了什么。在这种情况下,我不确定为什么我的user_input变量,在主函数块中声明并定义为"0",将在修改它的内部块中正确地被修改为"2",但随后在主函数块中被设置为"NULL"。
我的理解是,当在嵌套块中修改内容时,外部块不会识别这些更改——它们永远不会离开内部块的作用域。
我最好的猜测是它一定与我的文件打开和文件关闭有关,或者我不知道getline是如何与它们交互的。在过去的一年里,我做了很多cin和cout,但是没有接触过getline,也没有文件交互。
//fake_main.cpp
#include <fstream>
#include <iostream>
#include <string>
int main()
{
//---|Initializations|---
std::string user_input = "0";
//user_input is 0 in this block
std::ofstream outbound_filestream;
outbound_filestream.open ("a.txt");
outbound_filestream << "2" << std::endl;
outbound_filestream.close();
std::ifstream inbound_filestream;
//verifying that there is a "2" in my otherwise empty file
inbound_filestream.open ("a.txt");
if (inbound_filestream.is_open())
{
while (std::getline(inbound_filestream, user_input))
{
std::cout << user_input << 'n';
//user_input is 2
}
inbound_filestream.close();
//right here, after losing scope, user_input is NULL, not 0.
}
//and then, following suit, user_input is NULL here, not 0 or 2.
//---|Main Program|---
intro(user_input);
//snip
return 0;
}
while (std::getline(inbound_filestream, user_input)) {
}
将把输入读入user_input
变量,直到没有可用的输入。因此,您想要的内容只能在循环体中使用。
最后一个退出循环的循环将设置user_input
为空。
如果您想逐行收集流中的所有输入,您可能需要一个额外的变量来读取该行:
std::string line;
while (std::getline(inbound_filestream,line)) {
user_input += line;
}
相关文章:
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 大于65535的C++数组[size]引发不一致的溢出
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 在 C++(和 C)中进行类型转换时明显不一致
- 填充上编译器生成的复制构造函数之间的不一致
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- CreateDIBSection为同一图像返回不一致的位图位值
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- 在 Qml 中从 QSqlTableModel 中删除单行时视图不一致
- 模板参数推导不一致
- 声明中不一致的no是否违反ODR?
- 如何删除分支因子不一致的树,最大为 30,40
- 从 C++ 函数与 Python 函数返回的不一致值用于偏斜正态分布
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- 这种比较是否不一致(或者存在其他问题)?
- 以下可变参数模板行为是否不一致?
- 如何修复我的链表读数不一致的问题?
- NDK 问题:在 32 位上崩溃,在 64 位上不一致
- 解决SDL2按键检测不一致的问题
- 遇到getline、fstream、作用域不一致的问题