Ardit Zotaj
Ardit Zotaj

Reputation: 13

How to output from a txt file in C++. The file has one two rows

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;
}

Upvotes: 1

Views: 80

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

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.

Upvotes: 2

Related Questions