Search code examples
c++fstreamgetline

Stumbling across getline, fstream, scope inconsistency


I'm reading up on std::getline(), but I'm not figuring out what I'm doing wrong. In this scenario, I'm unsure why my user_input variable, which is declared in the main function block and defined as "0", will correctly be modified to "2" in an inner block that modifies it, but then be set to "NULL" afterwards in the main function block.

My understanding is that when things are modified in a nested block, the outer block does not recognize the changes--they never leaves the inner block's scope.

My best guess is that it must have something to do with my file-opening and file-closing things, or that I don't know how getline interacts with them. I've done lots of cin and cout over the past year, but haven't touched getline, nor file interaction either.

//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;
}

Solution

  • The lines

        while (std::getline(inbound_filestream, user_input)) {
        }
    

    will read input into the user_input variable until no more input is available. Thus the content you want to have is only available inside of the loop body.

    The last cycle that exits the loop, will set user_input empty.

    If you want to collect all the input from the stream line by line, you may have an extra variable to just read the line:

        std::string line;
        while (std::getline(inbound_filestream,line)) {
            user_input += line;
        }