Need help with search functions.

My program needs two functions. One to get user input for a student name and search for it in a string array. Another one to display the scores for that student. The data is coming from a text file and I was able to store the names and scores in arrays,

1
2
3
4
const int NUM_STUDENT = 10;
const int NUM_SCORE = 5;
string studentNames[NUM_STUDENT]
string studentScores[NUM_STUDENT][NUM_SCORE];


The problem is that how would I make a search function make sure it finds a valid name and display a specific row of scores for that particular student? Any help is appreciated!
My source code is below,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool inputStudentName(string name, string studentNames[]){
cout << "Enter student name in order to view scores: ";
cin >> name;
for(int k=0; k<NUM_SCORES; k++){
if(studentNames[k] == name){
return true;
}
else{
return false;
}
}
}
void displayScore(string name, int studentScores[][NUM_SCORES]){
if(inputStudentName(name)){
for(int i=0; i<NUM_SCORES; i++){
for(int j=0; j<NUM_SCORES; j++){
cout << name << " " << studentScores[i][j];
}
}
}
}
Last edited on
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
#include <iostream>
#include <string>

const int NUM_STUDENT = 10;
const int NUM_SCORE = 5;

// search for a student name in the names array.
// return position in the array if found, -1 if not found
int search( const std::string& name, const std::string student_names[NUM_STUDENT] )
{
    for( int i = 0 ; i < NUM_STUDENT ; ++i ) if( name == student_names[i] ) return i ;
    return -1 ; // not found
}

// display the scores for that student
void display_scores( const std::string& name, const std::string student_names[NUM_STUDENT],
                     const int scores[NUM_STUDENT][NUM_SCORE] )
{
    const int pos = search( name, student_names ) ;

    if( pos == -1 ) std::cout << "student name '" << name << "' not found\n" ;

    else
    {
        std::cout << "student name '" << name << "'  scores: " ;
        for( int s : scores[pos] ) std::cout << s << ' ' ;
        std::cout << '\n' ;
    }
}
Topic archived. No new replies allowed.