Hello, everyone! I am supposed to write codes for a little program that records names of students and their test scores. If I typed the same name twice, the program would prompt an error. If I type in "NO MORE", then the program stops recording and displays all the information. Here is the code:
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <complex>
#include <ctime>
usingnamespace std;
int main()
{
cout << "Please type a person's name and his/her score." << endl;
string name;
int score;
int x = 0;
vector<string>names;
vector<int>scores;
while(cin >> name >> score)
{
if (name == "NO MORE")
break;
for(int i = 0; i <=x; i++)
{
if(name == names[i])
{
cout << "Sorry. The name: " << name << " is entered twice." << endl;
cout << "Please type a person's name and his/her score." << endl;
}
else{
names.push_back(name);
scores.push_back(score);
cout << "Please type a person's name and his/her score." << endl;
x++;}
}
}
cout << "Program terminated by user." << endl;
for(int y = 0; y <= x; y++)
{
cout << names[y] << " --- " << scores[y] << endl;
}
}
// The program always stops working after I entered the first set of inputs like "Joe 87". I am using Code::Blocks with the GNU GCC Compiler.
Could someone help me investigate what is wrong with my code? Thank you very much!
Thank you vlad! I revised my code, but there is a new problem coming up: I typed a name only for once, but it will prompt me saying that I already entered the name twice. Could you help me investigate what is going wrong with the logic of my code? Thank you very much!
, whenever the "name" variable is not equal to one particular element of the "names" vector, the if statement will add the name to the end of the vector for multiple times except for the time when name equals to one particular element of the vector. So what I need to do the to get the push_back commands out of the for loop so no repetitive tasks will be done, since the names only need to be added ONCE.