Retrieving data program

OK so i have tried to figure out what is wrong with this program i did at least 2 hours of research and couldnt find anything. it is a pretty basic program. I have to retrieve a name and city from a data file and everytime I retrieve the data it only comes up with the first word for the city and name.
here is my program pls help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
string name;
string city;


ifstream infile;
infile.open("h:/testdata.dat",ios::out);

do
{
infile>>name;
if (!infile.eof() )
{
infile.ignore(70,'\n');
cout<<"name:  "<<name<<endl;
infile>>city;
infile.ignore(70,'\n');
cout<<"city:  "<<city<<endl<<endl;
}
}
while (!infile.eof() );

infile.close();

cin.ignore();
cin.get();

return 0;
}
Last edited on
The extraction operator>> stops processing when it encounters a white space character. If you want to retrieve a string that contains spaces you need to use something like getline(). For more information you will need to provide a small sample of your input file.

Also please edit your post to add code tags.
Last edited on
I tried using getline() but i didnt know how to use it to output. i used it when to input data into the file and i checked the data file to make sure everything went in right.

The data file just says

Mike wilson
salt lake

It comes out like
mike
salt
Last edited on
I finally figured it out i need to put getline(infile,name); instead of infile>>name;
That is because you are using the extraction operator>> to retrieve the string. The extraction operator stops when it encounters a white space character. You need to use getline() to extract the string. You don't use getline() for output, this is an input function. You should also not use eof() to control your data entry loop.

For your data something like this should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
   string name;
   string city;


   ifstream infile("h:/testdata.dat");

   while(getline(infile, name))
   {
      getline(city);
      cout<<"name:  "<<name<<endl;
      cout<<"city:  "<<city<<endl<<endl;
   }

   return 0;
}


Also note that you don't want to try opening an input stream with the output flag.

infile.open("h:/testdata.dat",ios::out);

Replace this:
1
2
3
4
5
6
7
8
9
10
11
12
13
do
{
infile>>name;
if (!infile.eof() )
{
infile.ignore(70,'\n');
cout<<"name: "<<name<<endl;
infile>>city;
infile.ignore(70,'\n');
cout<<"city: "<<city<<endl<<endl;
}
}
while (!infile.eof() );


with this:
1
2
3
4
5
6
    while (getline(infile,name))
    {
        cout <<"name: "<<name<<endl;
        getline(infile, city);
        cout <<"city: "<<city<<endl<<endl;
    }
Topic archived. No new replies allowed.