Hello everyone! Im new to programming and Im working on an assignment but I keep running into trouble. My assignment is to make a trivia game and although I have made pretty good progress, I am stuck on one particular part.

The part I am stuck at is I am trying to read a string variable into an array. I have no code yet because I am exactly sure how to approach this. The string variable holds questions so I want to read each question into the array that way I can call them in their perspective index. There is a space between each question in the string variable, is there a way to write a for loop to read each question into the array at a specific index?

Thanks for your help.

Recommended Answers

All 25 Replies

You should clarify what you mean either "read from an array" or "write into an array"... I'm not sure which one you mean.

If you have a string that contains all questions.. then I guess you have to do a for-loop for each character until you hit a '?' character and take the string before and including the ? and append it to the array, then continue with the rest of the string until there is nothing left. At the end you will have an array. You can use "std::vector<std::string>" for the array and "insert()" to add and operator [index] to get a question in particular. Well.. I'm sure you will want to use a struct or class that holds the question string and the right answer string too.

Since you keep saying "array", I wonder if you don't want a multi-dimensional char array?

char myCharArray [][80] =
    {"This is question 1",
     "This is question 2",
     "This is question 3",
     "This is question 4"};

If your assignment is for a C++ course, you better do this instead of the above:

std::vector<std::string> questionArray;
questionArray.push_back("This is question 1");
questionArray.push_back("This is question 2");
questionArray.push_back("This is question 3");
questionArray.push_back("This is question 4");

Your prof. or corrector might not be too happy to see C-style code in a C++ course assignment.

Actually, in my C++ courses, we did arrays and C-style strings before we did C++-style strings and vectors.

You should really learn the basic concepts before you jump into the STL, so that you can understand it. You need to walk before you can run.

Thank you for the replies. Sorry if I wansnt clear but I am trying to "write" to an array from the string variable.

Im not sure I understand vectors as I have never worked with them before. Am I doing this right to creating the vector variable? Im not sure how to construct the for loop to read the string variable into the array and stop when it reaches "?". Thanks again for your help.

const int SENTINEL = 6; //amount of questions but will be expanded
string questions;
vector<questions> questionArray;

for(int i = 0; i < SENTINEL; i++)
{
    
}

Also, from what I have read, I can use push_back("?") to add the question mark back in, correct?

Okay, I'll concede to mike, you are using vectors, not arrays. They are similar, but they are not the same. Please be cautious about using the terms interchangeably. A vector can be accessed like an array (using square braces), but they are much more powerful.

First, your declaration needs to be corrected. You are attempting to declare a vector of questions. Conceptually, this is fine. The problem is that there is no "question(s)" class/type in your program. A question is a string, so your vector should be declared as a vector of strings, not questions.

std::vector<std::string> myQuestionsVector;

Second, you can use std::vector::push_back() to add questions to the vector, but probably not to add the question-mark on to the end of the extracted string(s). You'll need some sort of concatenation operation to do that. Once you have done that, you can call push_back() with the new data to add it to the vector:

myQuestionsVector.push_back("some string literal");
myQuestionsVector.push_back(stringVariableHoldingAnExtractedQuestion);

I see, they share such a close resemblance that I thought they were pretty much the same. Using a vector then wouldn't satisfy the assignment requirements as it has to be an array.

I guess Im back to the array idea.

My biggest question is how do I write from the string variable into the array until it it hits "?". Also, does it matter if the array is char or string?

Thanks

Assuming for simplicity that the trivia is Jeopardy, and answers are separated by '|':

string answers = "42|George W. Bush|Burt Reynolds|Edmund Arantes Do Nancimento";
vector<string> answerArray;

int last_delimiter = 0;
int current_delimiter = answers.find('|',last_delimiter);
do {
  if(current_delimiter == -1) {
    answerArray.push_back(answers.substr(last_delimiter,answers.size() - last_delimiter));
    break;
  };
  answerArray.push_back(answers.substr(last_delimiter,current_delimiter - last_delimiter));
  last_delimiter = current_delimiter + 1;
  current_delimiter = answers.find('|',last_delimiter);
};

Well let me put the code on how I get the questions in the first place. I get them from an external file:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

string askQuestions()
{
	int counter = 0;
	string questions = " ", tempString = " ";
	ifstream inQuestions;
	const int SENTINEL = 6;


	//open necessary files
	inQuestions.open("trivia_questions.txt");

	//extracts words from external file and puts them into string
	for(counter; counter < SENTINEL; counter++)
	{
		getline(inQuestions, tempString);
		questions.append(tempString);
	}
	//close files
	inQuestions.close();

	return questions;
}

I initially tried a eof() loop but didnt have much success so I ended up appending the questions into one string variable. I return the quetions to main() where my idea is then to send it to another function called userInput where it will display the questions while also asking for the user's input. I want to return the user input back to main() where it calls the final function called answers where it writes the answers into another array and finally compares the answers to the users input.

Im basically making it this way because I am really new to programming and I dont quite understand all the basic concepts yet.

Thanks for your help.

Ohh so you have a file with each question on separate line.. then it all becomes so much easier. Just change "string questions" for "vector<string> questions" and replace the call "questions.append(...)" by "questions.push_back(...)". Then your function can return a "vector<string>" and you will have your array (or vector) of questions.

So to print one question simply call:
cout << questions[current_question_index] << endl; //or insert a "?" if the question mark is missing from the question string.

Thanks for the suggestion, this seems like it will work great. I am having problems returning the vector however, it keeps telling me "Illegal use of this type as an expression".

Is the syntax simply: return vector<string>

Thanks

You must have declared a variable as the type vector<string>, return that and change the function prototype to reflect the return value as vector<string>.

You must have declared a variable as the type vector<string>, return that and change the function prototype to reflect the return value as vector<string>.

Thanks, I must have made this harder than it looked. I returned it to main() and I was able to display the questions.

Thanks for your help everyone!

So I have made some pretty good progress since my last problem and I am nearing the end of my program but I have one last problem I cannot figure out. I keep getting the error "Cannot convert from std::string* to std::basic_string" on line 65. I posted my entire program to see if maybe I screwed something up somewhere else. I didnt want to start a new thread on what may be the same problem I was having earlier. Any help is appreciated. Thanks!

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctype.h>

using namespace std;

vector<string> askQuestions(int);
string* userInput(vector<string>, const int);
int answers(string, const int);


vector<string> askQuestions(const int SENTINEL)
{
	int counter = 0;
	string tempString = " ";
	vector<string> questions;
	ifstream inQuestions;

	//open necessary files
	inQuestions.open("trivia_questions.txt");

	//extracts words from external file and puts them into string
	for(counter; counter < SENTINEL; counter++)
	{
		getline(inQuestions, tempString);
		questions.push_back(tempString);
	}
	//close files
	inQuestions.close();

	return questions;
}

string* userInput(vector<string> questions, const int SENTINEL)
{
	string* tempArray = new string[SENTINEL];
	char tempInput[50];
	int counter = 0;

	do
	{
		cout << questions[counter];
		cin.getline(tempInput, 50);
		tempInput[0] = toupper(tempInput[0]);
		tempArray[counter].assign(tempInput);
		counter++;

	}while (counter != SENTINEL);
	
	return tempArray;
}


int answers(string userAnswers, const int SENTINEL)
{
	ifstream inAnswers;
	string grade = new string[SENTINEL];
	int score = 0, counter = 0;

	inAnswers.open("trivia_answers.txt");
	getline(inAnswers, grade);

	for(counter; counter < SENTINEL; counter++)
	{
		if(userAnswers[counter] == grade[counter])
		{
			score++;
		}
	}

	return score;
	

}


int main()
{
	int score = 0, counter = 0;
	const int SENTINEL = 6;
	string* tempArray = new string[];
	string userAnswers[SENTINEL];
	vector <string> questions;

	displayMenu();
	questions = askQuestions(SENTINEL);
	tempArray = userInput(questions, SENTINEL);

	for(counter; counter < SENTINEL; counter++)
	{
		userAnswers[counter] = tempArray[counter];
	}

	score = answers(userAnswers[SENTINEL], SENTINEL);

//	cout << "\nCongrats, your score is: " << score;

	cin.get();
	cin.get();
	return 0;
}

Sorry, the line number is different on here, its actually line 59.

'new' returns a pointer to the allocated memory so the variable should be a string* not a string.

You didn't need to say it was line 59, I spotted the mistake in a second, line 59 should be:

string* grade = new string[SENTINEL]; //Notice the * sign

And just for good programming practices, you should have a "delete[] grade;" statement before returning from the answers() function.

EDIT: you beat me at it Agni.

I guess I do not understand enough about pointers as now I have several errors after adding the "string*". Most of the errors have to do with lines 77 and 81. Says things like " cannot convert parameter 2 from 'std::string *' to 'std::basic_string".

Thanks Mike, I will delete the array before returning as you have suggested.

Then why are you declaring the string array dynamically? Since you already know the size of the array at compile time just say

string grade[SENTINEL];

and then add elements to the array like

grade[0] = "Pointers";

etc..

At line 63 you use getline() to write to an array of strings. You need to call this function for every string in the array:

string* grade = new string[SENTINEL];
  for(int i=0;i<SENTINEL;++i)
    getline(inAnswers, grade[i]);

Then why are you declaring the string array dynamically? Since you already know the size of the array at compile time just say

Well, thats what I originally had but I kept getting compiling errors like "expected constant expression", "cannot allocate an array of constant size 0", and "'grade' : unknown size"

At line 63 you use getline() to write to an array of strings. You need to call this function for every string in the array:

That is actually close to what I was trying, thanks it worked. I think my last problem is comparing the two indexes from each array at line 85.

Thanks for your help guys.

Line 56 should take an array of answers, like this:

int answers(string* userAnswers, const int SENTINEL) //notice the * again.

Line 96 should call the answers() function like this:

score = answers(userAnswers, SENTINEL); //notice the removal of [SENTINEL]

Line 56 should take an array of answers, like this:

Line 96 should call the answers() function like this:

I can't believe that's all it was. I have been hammering this thing for hours. Thanks for everyone's help, I can't tell you how much I appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.