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

时间:2017-08-25 14:14:08

标签: c++ cout

我做了一个程序:

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

现在我想一个接一个地展示问题。那么我该键入什么......? 像

cout << a(count);

这样问题就会按顺序显示。

提前致谢

2 个答案:

答案 0 :(得分:3)

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

为什么不使用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?

答案 1 :(得分:0)

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

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 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";
}

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