Enthused Binary
Enthused Binary

Reputation: 64

How to define char sizes in C++ in an array?

Recently, I have been working on a console project in which, when prompted to, the user will input 10 questions (Individually) and 10 answers (Individually) which will proceed to be the basis of a UI study guide.

Currently, here is my code (Snippet only):

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>


using namespace std;

int main() //The use of endl; in consecutive use is for VISUAL EFFECTS only 
{       
    char z;
    char a[500], b[500], c[500], d[500], e[500], f[500], g[500], h[500], i[500], j[500]; //Questions
    char a1[1000], b1[1000], c1[1000], d1[1000], e1[1000], f1[1000], g1[1000], h1[1000], i1[1000], j1[1000]; //Answers

    cout << "Hello and welcome to the multi use study guide!" << endl;
    cout << "You will be prompted to enter your questions and then after, your answers." << endl << endl;
    system("PAUSE");
    system("CLS");

    cout << "First question: ";
    cin.getline(a,sizeof(a));
    cout << endl;   
    system("PAUSE");
    system("CLS");

In this snippet, I am defining multiple char variables and assigning them a size, then retrieving user input to put into the specified variable.

My question being, how could I define the size of a single char variable in an array instead of using multiple variables in one line?

Upvotes: 0

Views: 1378

Answers (1)

Barmar
Barmar

Reputation: 781129

You can declare an array of char arrays:

#define NQUESTIONS 10
char question[NQUESTIONS][500];
char answer[NQUESTIONS][1000];

You can then use a loop to enter the questions and answers.

for (int i = 0; i < NQUESTIONS; i++) {
    cout << "Question #" << i+1 << ":";
    cin.getline(question[i], sizeof(question[i]));
}

But the C++ way to do these things is with a std::vector containing std::string.

Upvotes: 1

Related Questions