The code is as follow :
The Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int id;
char name[50];
ifstream myfile("savingaccount.txt"); //open the file
myfile >> id;
myfile.getline(name , 255 , '\n'); //read name **second line of the file
cout << id ;
cout << "\n" << name << endl; //Error part : only print out partial name
return 0;
}
The File Content:
1800567
Ho Rui Jang
21
Female
Malaysian
012-4998192
20 , Lorong 13 , Taman Patani Janam
Melaka
Sungai Dulong
The Problem :
1.)I expect the getline will read the name into the char array name and then I can print out the name , the thing is instead of getting the full name , I only get partial of the name , why this happen?
Thank you!
The problem is that
myfile >> iddoes not consume the newline (\n) at the end of the first line. Thus, when you callgetlineit will read from the end of the ID until the end of that line, and you will get an empty string. If you call againgetlineit will actually return the name.My advise would be to just use
std::getlinefor all the lines and if a line contains a number you can just convert it usingstd::stoi(if your compiler supports C++11) orboost::lexical_cast.