查找事件并打印星号而不是数字

时间:2015-02-25 15:26:43

标签: c++ arrays

当程序在数组中找到数字时,如何在程序中打印*而不是数字...例如,数组有10个元素,元素是:1,1,1,1,2,2, 2,2,1,2

程序应该显示输出为1 *****和2 *****。 我怎样才能做到这一点? 现在,这是我的代码:

int numbers[10],c,n;
    for(int i =0;i<10;i++)
    {
        cout<<"Enter Numbers ";
        cin>>numbers[i];
    }
    for(int i = 0;i<10;i++)
    {
        if(numbers[i]==-1)
        {
            continue;
        }
        n=numbers[i];
        c=1;
        for(int j =i+1;j<10;j++)
        {
            if(numbers[j]==n)
            {
                c++;
                numbers[j]=-1;
            }
        }
        cout<<n<<" is Stored "<<c<<" Time in the Array"<<endl;
    }

1 个答案:

答案 0 :(得分:0)

我在理解你的问题时遇到了一些困难,但我想你要打印一个星号(*)c次。您可以使用std::string的构造函数std::string(count, char)构建一个包含 count char 副本的字符串。

所以std::string(c, '*')正是你所寻找的,似乎是:

cout << n << " is Stored " << std::string(c, '*') << " Time in the Array" << endl;

请注意,using namespace std是不好的做法,因为它污染了命名空间。通常,您可能需要查看Google C++ Style Guide

相关问题