Cerealkiller050
Cerealkiller050

Reputation: 53

C++; Using strings getline() not working with file input

I can get getline() to work with cin (getline(cin,line)), but when I open a stream, it won't read the line from the file. The file contains a list of elements from the periodic table.

for Example:
H
He
O
etc...

EDIT:

However, when I try to cout the newly read line, it doesn't put it into var symbol at the line:
cout << "symbol: " << symbol << endl;

It doesn't give me anything out, but it should return the first element (H).

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

using namespace std;

void print(vector <string> x)
{
    cout << "list of elements:" << endl;
    for (int i = 0; i < x.size(); ++i)
    {
        cout << x[i] << endl;
    }
}

int main(int argc, char** argv) 
{
    string symbol;
    vector <string> elementlist;
    ifstream readin;

    readin.open("Elements.txt");
    getline(readin,symbol);
    cout << "symbol: " << symbol << endl;
    while (!readin.good())
    {
        elementlist.push_back(symbol);
        getline(readin,symbol);
    }
    print (elementlist);
    return 0;
}

Upvotes: 2

Views: 5239

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490128

I'd do it something like this:

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

class line {
    std::string data;
public:
    friend std::istream &operator>>(std::istream &is, line &l) {
        std::getline(is, l.data);
        return is;
    }
    operator std::string() const { return data; }    
};

int main() {
    std::ifstream readin("Elements.txt");

    // Initialize vector from data in stream:
    //
    std::vector<std::string> 
        element_list((std::istream_iterator<line>(readin)),
                      std::istream_iterator<line>());

    // write data from vector to cout:
    //
    std::copy(element_list.begin(), element_list.end(),
             std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}                              

Upvotes: 2

obataku
obataku

Reputation: 29646

As I stated in my comment, your loop condition is wrong.

while (!readin.good())
{
    elementlist.push_back(symbol);
    getline(readin,symbol);
}

As it turns out, you want to loop using the condition readin.good(). Since !readin.good() will evaluate to false, you never actually enter the loop.

Upvotes: 1

Related Questions