0

I'm having a strange issue with stoi(). Heres my code:

ifstream bookStream("inventory.txt", ios::in);
book tempBook;

string tmp;
if (bookStream.is_open())
    while (!bookStream.eof()) {
        getline(bookStream, tmp, '#');
        //cout << tmp << endl;
        tempBook.bookId = stoi(tmp);


        getline(bookStream, tempBook.title, '#');
        tempBook.title = tmp;
        getline(bookStream, tempBook.author, '#');
        tempBook.author = tmp;
        getline(bookStream, tmp, '#');
        tempBook.cost = stof(tmp);
        getline(bookStream, tmp, '#');
        tempBook.price = stof(tmp);
        getline(bookStream, tmp, '#');
        tempBook.quantity = stoi(tmp);

    }
else
    cout << "error opening file" << endl;

I get a runtime error (abort has been called). If I comment the bottom half of the code and just run:

getline(bookStream, tmp, '#');
cout << tmp << endl;

in the while loop it will print out every string just how it should, with integers and strings sperated on each line and no '#'. Even if i commented everything but the first stoi() it will throw the same error.

Here are a couple lines from my inventory.txt:

116807#A Tale of Two Cities#Charles Dickens#3.73#9.99#1
111272#The Iliad#Homer#2.78#9.99#10
164440#The Great Gatsby#F. Scott Fitzgerald#4.92#9.99#8

output of cout << tmp << endl;

http://i.imgur.com/4Tn4Rd8.png

Erd
  • 55
  • 7
  • TL;DR; `while (!bookStream.eof())` is wrong. Test `if(getline(bookStream, tmp, '#')` –  Mar 23 '15 at 19:45
  • Additional to @DieterLücking's comment, `getline(bookStream, tmp, '#');` doesn't take a line end (`'\n'`) into account as a delimiter any more! – πάντα ῥεῖ Mar 23 '15 at 19:49
  • getline seems to ignore `\n` if i output just what `tmp` becomes (see updated OP for pic) – Erd Mar 23 '15 at 19:55

0 Answers0