Using strings

I am trying to save questions to a vector and I have declared the vector as a string but the program does not work if I enter more that a word. Am I declaring the vector incorrectly?

Here is the code I have so far:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
	vector<string> questions;
	vector<string> answers;
	vector<int> finalScore;
	vector<string> studentName;
	int numOfStudents;
	int numOfQuestions;
	int score = 0;
	string studentAnswer;

	cout << "\t\tScoring System";
	cout <<"\nEnter the number of questions for the test: ";
	cin >> numOfQuestions;

	for(int i=1; i <= numOfQuestions; i++)
	{
		string question;
		string answer;
		cout <<"\nEnter question number "<< i <<"\n";
		cin >> question;
			questions.push_back(question);
		cout <<"\nEnter the answer for question number "<< i <<"\n";
		cin >> answer;
			answers.push_back(answer);
	}

	cout <<"\nHow many students will be taking this test? ";
	cin >> numOfStudents;

	string name;
	for( int i=1; i<=numOfStudents; i++)
	{
		cout <<"\nPlease enter your name: ";
		cin >> name;
			studentName.push_back(name);

			for(unsigned int i = 0; i<=questions.size(); ++i)
			{
				cout <<"\n" << questions[i];
				cin >>studentAnswer;
				
				for (unsigned int i=0; i <= answers.size(); ++i)
				{
					if(studentAnswer == answers[i])
					{
						score++;
					}
				}
			}
	}

}
1. Use getline instead of cin inside the loop of question and answers
2. Use < instead of <= in the student's question and answers loop.

string question;
string answer;
cout <<"\nEnter question number "<< i <<"\n";
cin >> ws; // added for whitespace
getline(cin, question);
questions.push_back(question);

cout <<"\nEnter the answer for question number "<< i <<"\n";
getline(cin, answer);
answers.push_back(answer);
Last edited on
Thanks meeram, that did it and learned a lot about vectors tonight
Topic archived. No new replies allowed.