1

I need to read from file and print line by line

Here is my file with colon separators

Miami:Sunny:USA
London:Rainy:England

and print as it's below:

City: Miami Weather:Sunny Country: USA
City: London Weather:Rainy Country: England

However I got this:

City:  Miami Weather:  Sun Country USA
London City:  Rain Weather:  England Country USA

Here is what I have done so far:

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

void read_from_file()
{
    string city;
    string c;
    string w;
    fstream file("list.txt");
    if (file.is_open())
    {
        while (file.good())
        {
            getline(file, city, ':');
            cout << " City:  " << name;
            getline(file, w, ':');
            cout << " Weather:  " << w;
            getline(file, c, ':');
            cout << " Country: " << c;
        }
        file.close();
    }
}

int main()
{
    read_from_file();
    return 0;
}

I think my problem colon in getline(file, w, ':'); but when I put '\n' instead it crashes.

Is there anybody who can help?

0x499602D2
  • 87,005
  • 36
  • 149
  • 233

3 Answers3

1

The newlines in your file happen after the country, so when you read in the country, you should be using a newline delimiter (this is done by default if you leave out the delimiter argument). It looks like you tried doing this when reading into w instead of c.

Instead of:

getline(file, c, ':');

Use:

getline(file, c);

Also, when you output, you will need to insert a newline yourself after your print the country.

cout << " Country: " << c << endl;

MahlerFive
  • 4,689
  • 4
  • 28
  • 40
1

You don't have any colons after your country so you shouldn't use it as a delimiter either.

Change

getline(file, c, ':');

to

getline(file, c);

so it'll use the default newline as delimiter.

Also your code would just output everything on one line so you might want to change

cout<<" Country: "<<c;

to

cout<<" Country: "<<c << '\n';

too.

Might consider reading Why is iostream::eof inside a loop condition considered wrong? too, checking for EOF or file.good() isn't usually the way to check the input. In your case it doesn't make any problems though.

Community
  • 1
  • 1
user1942027
  • 6,884
  • 6
  • 32
  • 44
0

The problem is that each line is not TERMINATED with a colon (:), but your getline is requesting a read upto the next ':', which is on the next line. Change it to use a newline on the LAST column.

Dwayne Towell
  • 6,895
  • 3
  • 32
  • 46