im struggling with this part of code , no matter what i try i cant get it to read into a record after two lines
the text file contains
Mickey Mouse 12121 Goofy 24680 Andy Capp 01928 Quasi Modo 00041 end
and the code is
#include<iostream>
#include<string.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;
struct record
{
char name[20];
int number;
};
void main()
{
record credentials[30];
int row=0;
fstream textfile;//fstream variable
textfile.open("credentials.txt",ios::in);
textfile.getline (credentials[row].name,30);
//begin reading from test file, untill it reads end
while(0!=strcmp(credentials[row].name,"end"))
{
textfile>>credentials[row].number;
row++;
//read next name ....if its "end" loop will stop
textfile.getline (credentials[row].name,30);
}
textfile.close();
}
the record is only taking the first two lines and the rest is empty
any ideas ??
The problem is that:
while not consume the newline character. The subsequent call to
textfile.getline()reads a blank line and the next:attempts to read
"Goofy"into anintwhich fails and set the failbit of thetextfilestream meaning all further attempts to read fail. Check the return value to detect failure:I am not entirely sure how the program ends as
"end"will never be read but I suspect it ends abnormally as there is no mechanism to prevent overruning the end of thecredentialsarray (i.e norow < 30as part of the loop terminating condition).Other:
Instead of using a fixed sized
char[]to read the names into you can usestd::getline():Instead of using a fixed sized
record[]you could use astd::vector<record>which will grow as required.