How do i get names outputted when i read a file

78 Views Asked by At

i am having trouble with reading names from a file the file contains a name and their score

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main(){
//
ifstream reader;
const int arraySize=100;
//storing names and score
char names[arraySize]; 
double scores[arraySize];
int count=0;
string toFind="";

// user input file 
do{
    cout <<"Enter a file name"<<endl;
string filename;
cout<<"**",cin>>filename;
//open file 
reader.open(filename.c_str());
// error if file name not found/invalid
if (!reader){
    cout<<endl;
    cout << "Error: Invalid file name."<<endl;
    cin.clear();
    cin.ignore();
}
}while(!reader);
cout<<endl;

// enter student name 

cout << "Enter a name"<<endl;
cout<<"**",cin>>toFind;

//print names
while(!reader.eof()){
    reader>>names;
    cout<<names;
}
// Close file 
reader.close();

return 0;
}

this is what I have so far I just need help on how to fix my while loop because it is outputting the numbers in the file when I first need it to output the names

the file looks like:

kelly 84

john 97

jane 99

kelly 91

kelly 95

jane 100

john 98

don 55

Note: my file opens fine but I'm not getting the names outputted

this is what i get when i run it:

Enter file name:

**

Enter a name:

**

kelly84john97jane99kelly91kelly95jane100john98don5555

right now i just need the names to be outputted without the scores first I am pretty sure the while loop is what needs fixing but I'm not sure how I am supposed to do that

1

There are 1 best solutions below

0
On

I think that you're closing the reader too early

Try moving this section to the end:

// Close file 
reader.close();

You will probably still get "Names Forward: " printing a bunch of times, and some output formatting issues, but this will at least get you data from the file.

Also, consider swapping this to this (added <<), as it won't compile everywhere otherwise

cout<<"Names Forward: " name[count];
cout<< "Names Forward: " << name[count];