c++ File Problem
Aug 24, 2013 at 3:34am UTC
Hi,everyone..this below is one of my functions..but currently having problem to read the file.It couldnt read the data properly.Can anyone plz assist on this?
Assume my filename is test.txt.
Content,
A12345//id
East W//name
567890//hp no
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
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
fstream inFile;
string id,name,hp_no;
inFile.open("test.txt" ,ios::in);
if (!inFile)
cout<<"Error opening file...\n" ;
while (!inFile.eof())
{
inFile>>id;
inFile>>name;
inFile>>hp_no;
}
cout<<"ID:" <<id<<endl;
cout<<"Name:" <<id<<endl;
cout<<"Hp No:" <<hp_no<<endl;
system("pause" );
return 0;
}
Aug 24, 2013 at 3:46am UTC
Looping on
eof like that is wrong.
You read different values into the same variables multiple times without using the values before they're overwritten.
Presumably you didn't mean to output
id on line 22.
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
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
const char * filename = "test.txt" ;
std::ifstream inFile(filename) ;
if ( inFile.is_open() )
{
std::string id, name, hp_no ;
while (std::getline(inFile, id) && std::getline(inFile, name) && std::getline(inFile, hp_no))
{
std::cout << "ID: " << id ;
std::cout << "\nName: " << name ;
std::cout << "\nHp No: " << hp_no << std::endl ;
}
}
else
std::cout << "Unable to open file \"" << filename << "\"\n" ;
}
Aug 24, 2013 at 3:58am UTC
Hi,ty for replying..
By referring to ur codes..i redo my codes as following..is it ok?
Becoz i dun really familiar with std:: yet..-the usage..
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
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
fstream inFile;
string id,name,hp_no;
char tmp[30];
inFile.open("test.txt" ,ios::in);
if (!inFile)
cout<<"Error opening file...\n" ;
while (!inFile.eof())
{
inFile>>id;
cout<<"ID:" <<id<<endl;
inFile.getline(tmp,30);
getline(inFile,name);
cout<<"Name:" <<name<<endl;
inFile>>hp_no;
cout<<"Hp No:" <<hp_no<<endl;
cout<<endl;
}
system("pause" );
return 0;
}
Topic archived. No new replies allowed.