0

I want to load data from .txt file to variable and working with them (like calculate). When I open data, I can read them, but I don´t know to work with data.

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

using namespace std;


int main()
{
    fstream newfile;
    string file;

    newfile.open("zadanie.txt", ios::in);
    if (newfile.is_open()) {   

        while (getline(newfile, file)) { 
            cout << file << "\n"; //I GET OUTPUT CORRECTLY
        }

        newfile.close();
    }
    else
        cout << "Error. \n";

    cout << file << "\n"; //HERE IS PROBLEM. OUTPUT IS EMPTY


    return 0;
}

I tried global variable, but it not solved. What should I do to correct it? Thanks

Lukas
  • 73
  • 7
  • 2
    This might be putting the cart before the horse. How do you want to store the lines of the file? You should first define that. A reasonable choice would be `std::vector`. Only then should you decide how to fill the variable you defined. – MSalters Nov 14 '19 at 16:51
  • each line you read replaces the previous content of `file`. You need to have a strategy on how to handle those lines further down the line – T3 H40 Nov 14 '19 at 16:52
  • If `newfile` fails to open, your `file` string will be empty. – Thomas Matthews Nov 14 '19 at 17:39

1 Answers1

1

What you call "PROBLEM" in the comment is not a problem. file never contains more than a single from the file. The last call to getline will not read a line because there is nothing left in the file when you reach its end. So when you call

std::cout << file; 

after that loop, it is to be expected that file is empty. If you want to use the lines later you should store them somewhere, eg in a std::vector<std::string>> :

int main()
{
    fstream newfile;
    std::vector<std::string> data;          // vector to hold all lines

    newfile.open("zadanie.txt", ios::in);
    if (newfile.is_open()) {   
        string line;                        // better name (file->line)
        while (getline(newfile, line)) { 
            cout << line << "\n";
            data.push_back(line);            // add the line to data
        }    
        newfile.close();
    }
    else
        cout << "Error. \n";

    for (const auto& l : data) std::cout << l << '\n';


    return 0;
}
463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126