#Beginner file input question

11 messages · Page 1 of 1 (latest)

wise plover
#

I'm trying to take input from a file and convert it into variables. I want each line of the file (including whitespace) to get stored as a string in its own variable. Right now I have

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{    
    cout << "Please enter the file name: " << endl;

    string filename;
    cin >> filename;
    ifstream f (filename);

    if(f.is_open())
    {    
        string line1;
        string line2;
        string line3;
        string line4;
        f >> line1 >> line2 >> line3 >> line4;
    }
    else
        cout << "Invalid File Name" << endl;
    return 0;
}

The issue being if line 1 is "John Doe" it'll make line1 variable be "John" and line2 be "Doe".
I know I should use getline somehow, but I don't exactly understand how. I tried getline(f, line1 >> line2 etc but it didn't like that lol

clear cragBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

wise plover
#

my intuition is to put the variables in a list, then do a for loop indexing the list to say which variable the current line should be put in, but we haven't talked about how lists work in c++ (I've only done matlab + python before)

glacial vale
#

You are on the right track, cause you indeed need to use getline() if you don't want the input to be split by spaces
Here's an example of how to do it:

#

;compile -Wall -Wextra -Werror -fsanitize=address,undefined

hello big
cruel world
#include <iostream>
#include <string>

int main() {
    std::string foo;
    std::getline(std::cin, foo);
    std::string bar;
    std::getline(std::cin, bar);
    std::cout << foo << " " << bar << "\n";
}
broken ibexBOT
#
Program Output
hello big cruel world
glacial vale
#

I want each line of the file (including whitespace) to get stored as a string in its own variable
Assuming that your file won't always have say exactly 3 lines of code, I recommend storing the strings in a std::vector, since it can grow to hold any number of strings. I'll give you the opportunity to look up std::vector, so you can give it a go :)

limpid lichen
glacial vale
wise plover
#

sorry for late response, had to go to work lol. So does getline grab the next line if it’s already been used in the code? That’s what it looks like but I may be mistaken

wise plover
#

Okay it looks like that's working, thanks!!