2011-11-27 61 views
0

如何编写一个程序读入键盘中的一组字符并将它们输出到控制台。数据随机输入,但有选择地输出。只有唯一的字符显示在控制台上。因此,无论数组出现多少次,每个字符都应该显示一次。C++:数组函数

例如,如果一个数组

Char letterArray[ ] = {B,C,C,X,Y,U,U,U}; 

输出应该是:

B,C,X,Y,U 

这是我迄今所做的......

char myArray [500]; 
int count = 0; 
int entered = 0; 
char num; 

while (entered < 8) 
{ 
    cout << "\nEnter a Character:"; 
    cin >> num; 

    bool duplicate = false; 
    entered++; 

    for (int i = 0; i < 8; i++) 
    { 
     if (myArray[i] == num) 
      duplicate=true; 
    } 

    if (!duplicate) 
    { 
     myArray[count] = num; 
     count++; 
    } // end if 
    else 
     cout << num << " character has already been entered\n\n"; 

    // prints the list of values 
    cout<<"The final Array Contains:\n"; 

    for (int i = 0; i < count; i++) 
    { 
     cout << myArray[i] << " "; 
    } 
} 
+2

问题或疑问是什么? – Zohaib

+0

角色是否需要按照输入的顺序出现? –

+0

你的代码似乎做得很好 –

回答

0

我相信你可以使用std::set<>

集是一种关联容器中存储的独特元素 < ...>一组元素总是从低排序,以更高以下具体严格弱排序标准设置

0

它创建一个128位数组(假设你正在处理ASCII码),这个数组将被初始化为false。每当你得到一个字符时,检查它的ASCII值,如果数组是真的,你不打印它。之后,将字符值上数组的值更新为true。喜欢的东西:

bool *seenArray = new bool[128](); 

void onkey(char input) { 
    if(((int)input) < 0) return; 
    if (!seenArray[(int)input]) { 
     myArray[count] = input; 
     count++; 
     seenArray[(int)input] = true; 
    }   
} 
+0

ASCII只定义[0,127)范围内的值。 –

+0

错误:如果存在非ASCII输入,则“if”行会从数组边界中进行访问,并且出现未定义的行为。通过将'if(int(input)<0)return;'添加到'onkey'的开头来修复。 –

+0

固定,谢谢... – idanzalz

0

通过您的代码看...

char myArray [500]; 

为什么500?你永远不要超过8个。

char num; 

令人困惑的命名。大多数程序员会希望名为num的变量是数字类型(例如intfloat)。

while (entered < 8) 

考虑一个具有恒定(例如const int kMaxEntered = 8;)替换8

cin >> num; 

cin可能是行缓冲的;即在输入整行之前它什么都不做。

for (int i = 0; i < 8; i++) 
{ 
    if (myArray[i] == num) 
     duplicate=true; 
} 

您正在访问未初始化的元素myArray。提示:您的循环大小不应该为8.

如果发现重复,请考虑使用continue;

if (!duplicate) 
{ 
    myArray[count] = num; 
    count++; 
} // end if 
else 
    cout << num << " character has already been entered\n\n"; 

您的// end if评论有错误。 if直到完成else才会结束。

您可能希望围绕else子句添加大括号,或通过将其两条线组合成单行myArray[count++] = num;,从if子句中删除大括号。

// prints the list of values 
cout<<"The final Array Contains:\n"; 

for (int i = 0; i < count; i++) 
{ 
    cout << myArray[i] << " "; 
} 

您每次单击输入时打印列表?

不要在文本中使用\ncout,除非您特意要微操纵缓冲。相反,使用endl。此外,总是在二进制运算符周围放置空格,如<<,并且不要随机大写单词:

cout << "The final array contains:" << endl; 
for (int i = 0; i < count; i++) 
    cout << myArray[i] << " "; 
cout << endl;