sending and retrieving data programs

Mar 26, 2013 at 1:55pm
So i made 2 programs one is suppose to send data to a data file and the other is suppose to retrieve the data. i noticed that when it retrived data it only came up with the first word so i opened the data file and it only had the first word of everything i typed in. My teacher said something about using getline instead of cin but i cant figure out how to use it or even if thats what im suppose to do pls help.
Heres my program that sends data to the file

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

int main()
{
string name;
string city;
char ans;

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

do
{
cout<<"enter name --> ";
cin>>name;
cin.ignore(70,'\n');
cout<<endl<<endl<<"Enter city --> ";
cin>>city;
cin.ignore(70,'\n');
outfile<<name<<endl;
outfile<<city<<endl;
cout<<endl<<endl<<"Do another (Y/N)? ";
cin>>ans;
cin.ignore(70,'\n');
cout<<endl<<endl;
}
while (ans != 'N');

outfile.close();
return 0;
}
Mar 26, 2013 at 2:01pm
closed account (3qX21hU5)
Change the cin's like cin >> name; to getline(cin, name); cin is the input method and name is the variable you would like to store in.
Basically getline can read more then one word where cin only reads one word because it stops at white spaces.

That should solve that problem though I haven't looked through the rest of your code. Let me know if you don't understand anything or need more help.

Mar 26, 2013 at 2:06pm
ok that fixed it but now theres a new problem my retrieve program only retrieves the first word in the data file.
heres the program

#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;
}
Mar 26, 2013 at 2:08pm
closed account (3qX21hU5)
I'll leave that for you to figure out :) Hint: It is almost the same as the first question you asked. Just do some research on it and I am sure you will have no problem figuring it out.
Mar 26, 2013 at 2:11pm
ok ill try to
Topic archived. No new replies allowed.