getline()与stoi()一起抛出奇怪的错误

时间:2015-03-23 19:40:51

标签: c++ ifstream getline

我对stoi()有一个奇怪的问题。继承我的代码:

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;

我收到运行时错误(已调用abort)。如果我评论代码的下半部分并运行:

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

在while循环中,它将打印出每个字符串应该如何,每行都有整数和字符串,没有“#”。即使我评论了除第一个stoi()之外的一切,它也会抛出相同的错误。

以下是我的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

cout << tmp << endl;

的输出

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

0 个答案:

没有答案