Помогите с программой C++
Итак, я только начинаю нелегкий путь в C++, так что решил сделать несложную программу: выдача вопросов и счет баллов за них. В суть углубляться не буду, но идея работы программы такая: в подключаемом файле я создаю и инициализирую двумерный вектор, каждый элемент которого строка с вопросом, так же я храню кол-во тем. Сейчас для примера будет 1 тема, но это не важно. Важно то, что при попытке сделать это получаю каскад ошибок, и вопрос: что я делаю не так и как это сделать лучше? Код:
#ifndef QPACK1_H
#define QPACK1_H
int theme_amount = 1;
std::vector<std::vector<std::string> > questions(theme_amount + 1, std::vector<std::string>(6, " "));
questions[1][0] = "Вы попали на тему: Name of the theme\n" ; // сначала номер темы, потом номер вопроса(по 5), 0 вопрос - название темы.
questions[1][1] = "Question 1";
questions[1][2] = "Question 2";
questions[1][3] = "Question 3";
questions[1][4] = "Question 4";
questions[1][5] = "Question 5";
#endif
Список ошибок:
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(8,1): error C2466: невозможно выделить память для массива постоянного нулевого размера
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(8,17): error C2087: questions: отсутствует индекс
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(8,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(10,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(10,1): error C2040: questions: "int [1][1]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(11,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(11,1): error C2040: questions: "int [1][2]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(12,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(12,1): error C2040: questions: "int [1][3]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(13,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(13,1): error C2040: questions: "int [1][4]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(14,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\qpack1.h(14,1): error C2040: questions: "int [1][5]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\CHGK_game.cpp(44,52): error C2088: [: недопустимо для class
1>C:\Users\User\source\repos\ConsoleApplication2\ConsoleApplication2\CHGK_game.cpp(46,48): error C2088: [: недопустимо для class
Основной код программы:
#include <vector>
#include <iostream>
#include <string>
#include "qpack1.h" //список вопросов
struct players
{
std::vector<std::string> name;
std::vector<int> score;
};
int main()
{
int pl_amount, qst_number = 0;
players plist;
std::string input;
std::cout << "Enter number of players(less then 10): ";
std::cin >> pl_amount;
plist.name.resize(pl_amount);
plist.score.resize(pl_amount);
plist.score.assign(plist.score.size(), 0);
std::cout << "Enter players names: \n";
for (int i = 0; i < pl_amount; i++)
std::cin >> plist.name[i];
std::cout << "Tips: enter stop to left the game. \nUse + or - and number of player to give(take out) points to his score.\n";
for (int theme_number = 1; theme_number <= theme_amount; theme_number++)
{
while (qst_number <= 4)
{
qst_number++;
if (qst_number == 1)
std::cout << questions[theme_number][0] << "\n";
std::cout << questions[theme_number][qst_number] << "\n";
TryAgain:
getline(std::cin, input);
if (input == "stop")
goto Results;
if(input.size() != 2 || !(input[1] > '0' && input[1] <= '9'))
{
std::cout << "Incorrect input.\n";
goto TryAgain;
}
if(input[1] - '0' > pl_amount || input[1] - '0' <= 0)
{
std::cout << "Incorrect input(Player was not found).\n";
goto TryAgain;
}
if (input[0] == '+')
{
plist.score[input[1] - '0' - 1] += qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets + " << qst_number * 10 << " points!\n";
}
else
if (input[0] == '-')
{
plist.score[input[1] - '0' - 1] -= qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets - " << qst_number * 10 << " points!\n";
}
else { std::cout << "Please start input with + or -.\n";goto TryAgain; }
}
qst_number = 0;
}
Results:
std::cout << "The final score is: \n";
for (int j = 0; j < pl_amount; j++)
std::cout << plist.name[j] << " : " << plist.score[j] << " points. \n";
}
И еще есть проблема: при первом выводе темы и вопроса, сразу же после этого выводится Incorrect input, хотя ничего не было введено. (проверял заккоментив эту часть: )
questions[1][0] = "Вы попали на тему: Name of the theme\n" ; // сначала номер темы, потом номер вопроса(по 5), 0 вопрос - название темы.
questions[1][1] = "Question 1"; questions[1][2] = "Question 2"; questions[1][3] = "Question 3"; questions[1][4] = "Question 4"; questions[1][5] = "Question 5";
В общем, как фиксить?)
Ответы (1 шт):
В файле qpack1.h
extern const std::vector<std::vector<std::string> > questions;
В файле qpack1.cpp:
const std::vector<std::vector<std::string> > questions = {
{ "Вы попали на тему: Name of the theme\n",
"Question 1",
"Question 2"
"Question 3"
"Question 4"
},
{ "Вы попали на тему: Name of the theme\n",
"Question 1",
"Question 2"
"Question 3"
"Question 4"
},
}