Reading in numbers and names using getline in C++?

879 Views Asked by At

So I've been working on this problem for hours now and I would like to get some help. I have a program due tomorrow. Basically, I have an input file that has a first and last name and then four float numbers following. It looks like this:

John W.
Smith
78.8 56.5 34.5 23.3
Jane 
Doe
34.5 23.4 35.7 87.0
No
More

I need to read the first and last names into an array of pointers. So far I am just trying to read in each line to the variable "name" and I'm outputting to a text file to see if I have been reading in the data correctly. Unfortunately, it stops after it reads in the floats, it doesn't read in the next names.

char *newPtr;               
char *nameList[50] = {0};   
char name[15];  
int i = 0; 
infile.getline(name, 15);

while (strcmp (name, "No") != 0)
{
    newPtr = new char[15];
    strcpy(newPtr, name);
    nameList[i] = newPtr;
    infile.getline(name, 15);
    outfile << name << endl;
    i++;
}

So far, the output has just been:

John W.

Smith

78.8 56.5 34.5 23.3

EDIT: The loop is currently infinite, but from my output, I know that I haven't actually processed the second names yet, I stop at the first numbers.

If I could get some help, it would be great! I am very limited to the functions I can use, I am certain I should just be using the getline function here, I cannot use anything fancy.

In her slides, my teacher has this code here to help us with reading in names:

char *newPtr;
char *NameList[6] = {0};
char Name[20];
int a = 0;
infile.getline(Name, 20);
while(strcmp(Name, sentinel) != 0)
{
newPtr = new char[20];
strcpy(newPtr,Name);
NameList[a++] = newPtr;
infile.getline(Name,20);
}

We have not been taught about strings yet and I am certain I cannot use what we have not talked about in class. Thank you for the help so far everyone who has commented.

1

There are 1 best solutions below

0
On BEST ANSWER

You're nearly there... main thing was you forgot to attempt to read the numbers. The code below reads them into w, x, y and z but then ignores them... you should do whatever you need to with them, e.g. probably create a second array for the surnames and either a third 2-dimensional array for the floats or a 1-dimensional array 4 times as long....

char *nameList[50] = {0};   
char name[15];  
int i = 0; 

while (infile.getline(name, sizeof name) && strcmp(name, "No") != 0)
{
    char* newPtr = new char[sizeof name];
    strcpy(newPtr, name);
    nameList[i] = newPtr;
    double w, x, y, z;
    if (infile.getline(name, sizeof name) && infile >> w >> x >> y >> z)
        outfile << name << endl;
    else
    {
        std::cerr << "missing rest of data for " << nameList[i] << " found\n";
        exit(EXIT_FAILURE)
    }
    i++;
}