【问题标题】:How do I print the elements of an array one at a time?如何一次打印一个数组的元素?
【发布时间】:2017-01-23 15:23:54
【问题描述】:

我已经用 C++ 编写了以下代码。这是用于生成随机字母和/或数字序列的程序,一次向用户显示一秒钟左右,然后要求用户重现序列。它使用队列来存储字符序列。我想修改代码,以便一次打印一个数组的元素。请帮助我。

#include <iostream>
#include<cstdlib>
#include <queue>
using namespace std;
int main()
{

std::queue<int> myqueue;
int array[6];
for (int i = 0; i < 6; i++)
{

    array[i]=rand()%100;

    printf("\n%d", array[i]);

    if(i==5) 
    {
        printf("\n Reproduce the sequence again");
    }

}

【问题讨论】:

  • 不太确定我是否理解,您的意思是要在显示每个元素后清除屏幕?
  • 如果你想要便携性,请使用ncurses
  • 清除屏幕是一个平台问题,因为标准 C++语言没有屏幕功能(并非每个平台都需要有屏幕)。
  • 您想在每个号码后延迟吗?你想让程序在每个数字之后sleep吗?您希望用户在每个数字后按 Enter 吗?您希望用户在每个数字后按任意键吗?请用答案编辑您的帖子。

标签: c++ arrays queue


【解决方案1】:

我不完全确定您的期望(我想是记忆游戏),但让我们看看这个。我正在使用 usleep,我确定 Windows 存在等效的东西

#include <unistd.h> // Required for usleep
#include <iostream> // cin, cout, flush
#include <stdlib.h> // rand

int main () {

    int array[6]; // Note : This will only give you an array of digits, not letters

    for (int i = 0; i < 6; i++)
    {

        array[i]=rand()%100;

        // "\r" is a carriage return, it moves the writing to the beginning of the line
        std::cout << "\r" << array[i] << std::flush;

        // sleeps 1 second
        usleep(1000000);
    }


    printf("\r Reproduce the sequence again (use space to separate, enter to validate");
    std::string userAnswer;
    std::cin >> userAnswer;

    // parse userAnswer

}

【讨论】:

  • 对于 C++11 及更高版本,您可以使用 std::this_thread::sleep_for
  • 我不确定 C++11 是否可用,但这确实是一个很好的选择 :)
  • 你还必须写固定宽度的数字,因为写100后跟2会显示200
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2014-12-15
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多