0

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?

7
  • 2
    Why don't you use std::string? char arrays are a remnant from C. Commented Oct 2, 2015 at 23:51
  • Are you asking how do to char question[10][500];? Commented Oct 2, 2015 at 23:52
  • Yes, I am asking how to do char question[10] with individual char sizes. (Hopefully that makes sense) Commented Oct 2, 2015 at 23:58
  • Obviously it does, since I already posted an answer. Commented Oct 2, 2015 at 23:59
  • To note, I just started working with C++ about 3 months ago. I have used namespace std; in each project and have little knowledge upon using std:: instead. Commented Oct 3, 2015 at 0:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Much more efficient than my current code. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.