1

The rows are as in the example:

583-4-153-15601-4  '\t' Time Warp Trio  '\t'  Scieszka Jon    '\t' 50  '\t'  50
583-0-133-15601-2  '\t'  Djemte e rruges pal    '\t'    Ardit Zotaj '\t' 50  '\t'  50

So Every string is separated by a tab. Basically it contains the information for a book.

ISBN-TITLE-AUTHOR-PRICE-NO. OF COPIES.<
//583-4-153-15601-4  '\t' Time Warp Trio  '\t'  Scieszka Jon    '\t' 50  '\t'  50
//583-0-133-15601-2  '\t'  Djemte e rruges pal    '\t'  Ardit Zotaj '\t' 50  '\t'  50

I have done this work so far but it doesn't give the right output me in the cmd.

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{ 
    ifstream fin;
    fin.open("bookdata.txt");
    string line;
    string isbn, title, author;
    int var1 = 0;
    int var2 = 2;

    while (!fin.eof())
    {
        getline(fin, isbn, '\t');
        getline(fin, title, '\t');
        getline(fin, author, '\t');
        fin >> var1;
        fin >> var2;
    }

    cout << isbn << title << author << endl;
    fin.close();
    cout << var1 << var2 << endl;
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • simply i want just to show the rows as they are in the text file. – Ardit Zotaj Jan 10 '16 at 18:34
  • Why does it have to be `!fin.eof()` every time, why??? `std::getline` returns the stream, which is implicitly convertible to `bool`, you could AND them together... If you could say more about the output, other than "it's right/wrong" that would be great. – LogicStuff Jan 10 '16 at 18:37
  • @LogicStuff the output it doesn't show anything. – Ardit Zotaj Jan 10 '16 at 18:38
  • @LogicStuff idk why is (!fin.eof()) that's what they taught us in school – Ardit Zotaj Jan 10 '16 at 18:39
  • @ArditZotaj : No book that I've ever seen teaches or encourages `while (!fin.eof())`. The reason? It's wrong! – ildjarn Jan 10 '16 at 18:53
  • @ildjarn we don't have any book. We use the translation of english books. And the teachers are not so good in english. We don't have PC in the class. We have a blackboard. – Ardit Zotaj Jan 10 '16 at 18:56

1 Answers1

2

Try something like this (not tested):

while (getline(fin, isbn, '\t') && getline(fin, title, '\t') &&
       getline(fin, author, '\t') && fin >> var1 && fin >> var2 &&
       fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'))
{
    cout << isbn << title << author << " " << var1 << " " << var2 << endl;
}

I used fin.ignore, so that we don't get \n, which is still in the stream after fin >> var2, as the first character of the next isbn. It could be also fin.ignore(1, '\n')...

You also have to print these variables in the loop, otherwise you'll just print the information of the last row in the file.

I also noticed, that you have string line; lying around. Another approach, now utilizing this object can be found here.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74