遇到getline、fstream、作用域不一致的问题

Stumbling across getline, fstream, scope inconsistency

本文关键字:问题 不一致 fstream getline 遇到 作用域      更新时间:2023-10-16

我正在阅读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;
    }