使用 while 循环显示顺序变量的值

Display sequential variable's value with while loop

我制作了一个程序:

char a1[100]="Ques 1" , a2[100]="Ques 2" , a3[100]="Ques 2";
int count=1;
while (count<=3)
{
  cout << ....;
}

现在我想一个接一个地展示题目。那么我应该在 .... 的位置输入什么? 喜欢

cout << a(count);

以便问题按顺序显示。

提前致谢

您为每个问题使用了不同的变量,这使得输出阶段难以组织。

为什么不使用 std::string 的数组?

std::string questions[] = {"Quesstion one", "Question two", "Question three"};

并使用

输出
for (auto& question : questions){
    std::cout << question;
}

这利用了 C++11 中的创新。

最后,为了将文本文件读入 std::vector<std::string>,请参阅 Reading line from text file and putting the strings into a vector?

如果您必须使用字符数组,您将需要一个字符数组数组。

const size_t MAX_QUESTION_LENGTH = 100;
const size_t MAX_QUESTIONS = 5;

char question_texts[MAX_QUESTIONS][MAX_QUESTION_LENGTH] =
{
  "Question 1",
  "Question 2",
  //...
  "Question 5",
};

int main()
{
  for (size_t i = 0; i < MAX_QUESTIONS; ++i)
  {
    std::cout << "\n"
              << question_texts[i]
              << "\n";
  }
  return 0;
}

另一种选择是使用 vector of string:

std::vector<std::string> question_database;
//...
question_database.push_back("Question 1");
//...
for (i = 0; i < question_database.size(); ++i)
{
  std::cout << "\n"
            << question_database[i]
            << "\n";
}

数组必须在编译时指定其容量。
字符串和向量在运行时动态增长。