如何在数组中定义 C++ 中的字符大小?
How to define char sizes in C++ in an array?
最近,我一直在做一个控制台项目,当出现提示时,用户将输入 10 个问题(单独)和 10 个答案(单独),这将继续成为 UI学习指导。
目前,这是我的代码(仅代码段):
#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");
在此代码段中,我定义了 多个 字符变量并为它们分配了大小,然后检索用户输入以放入指定变量。
我的问题是,如何在数组中定义单个 char 变量的大小,而不是在一行中使用多个变量?
您可以声明一个 char 数组数组:
#define NQUESTIONS 10
char question[NQUESTIONS][500];
char answer[NQUESTIONS][1000];
然后您可以使用循环输入问题和答案。
for (int i = 0; i < NQUESTIONS; i++) {
cout << "Question #" << i+1 << ":";
cin.getline(question[i], sizeof(question[i]));
}
但是 C++ 方法是使用包含 std::string
.
的 std::vector
最近,我一直在做一个控制台项目,当出现提示时,用户将输入 10 个问题(单独)和 10 个答案(单独),这将继续成为 UI学习指导。
目前,这是我的代码(仅代码段):
#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");
在此代码段中,我定义了 多个 字符变量并为它们分配了大小,然后检索用户输入以放入指定变量。
我的问题是,如何在数组中定义单个 char 变量的大小,而不是在一行中使用多个变量?
您可以声明一个 char 数组数组:
#define NQUESTIONS 10
char question[NQUESTIONS][500];
char answer[NQUESTIONS][1000];
然后您可以使用循环输入问题和答案。
for (int i = 0; i < NQUESTIONS; i++) {
cout << "Question #" << i+1 << ":";
cin.getline(question[i], sizeof(question[i]));
}
但是 C++ 方法是使用包含 std::string
.
std::vector