- #1
Of Mike and Men
- 54
- 3
Homework Statement
First of all, this ISN'T homework. This is independent study. I am in a CS program, but I am going through PPP by Bjarne Stroustrup to keep the language fresh. I'm working on one of the last assignment in chapter 4 which is this:
Write a program where you first enter a set of name·and·value pairs,
such as Joe 17 and Barbara 22. For each pair, add the name to a vector
called names and the number to a vector called scores (in corresponding
positions, so that if names[7]=="Joe" then scores[7]==17). Terminate
input by the line No more ("more" will make the attempt to read another
integer fail ). Check that each name is unique and terminate with an error
message if a name is entered twice. Write out all the (name,score) pairs,
one per line
I know my code isn't complete but I cannot get my for loop to run. I've ran various test cases, the while-loop is working, and it completes the full iteration of the while-loop. However, my for-loop never executes. It simply skips it (that is, code within the while-loop that appears before the for-loop and after the for-loop execute during each iteration). I.E. where hello1 and hello2 appear in the code, these execute fine.
Homework Equations
The Attempt at a Solution
[/B]
I'm pretty sure it has to do with my < sign in the for loop since <= will execute the for-loop but crash the program.
C:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> all_names;
vector<int> all_scores;
string names;
int scores;
while(cin>>names>>scores){
cout << "hello1";
for(int i = 0; i < all_names.size(); i++ ){
if( all_names[i] == names ){
cout << "duplicate name.";
}
else{
all_names.push_back(names);
all_scores.push_back(scores);
}
cout << "hello2";
}
}
return 0;
}
C:
while(cin>>names>>scores){
bool valid = true;
for( int i = 0; i < all_names.size(); i++ ){
if( all_names[i] == names ){
valid = false;
}
}
if(valid){
all_names.push_back(names);
all_scores.push_back(scores);
}
else{
cout << "duplicate name";
}
}
Last edited: