2016-12-15 85 views
1

我正在尝试编写一个C++程序,用非重复的字母从a-z(ascii代码97到122)打印一个随机的10个字母的字符串。我写过这段代码,有时可以完美运行,但while循环无限运行的大部分时间。 问题在哪里?如何打印非重复字母的随机字符串?

(编辑:在同时开始设置标志= 0解决了这个问题)

void randomstring() 
{int i,j,flag=1; 
char x, s[20]=" "; 
srand(time(0)); 
for(i=0;i<10;i++) 
{flag=1; //ensure entry into while 
    while(flag) 
    {x=rand()%26+97; //get random letter from a-z 
    for(j=0;j<10;j++) 
    {if(x==s[j]) //match with existing letters 
    flag=2; //if matched, try again 
    } 
    if(flag!=2) 
    {s[i]=x; //if doesn't match, add to string 
    flag=0; //exit while 
    } 
    } 
} 
cout<<s; 
} 
+0

[可能的重复](http://stackoverflow.com/questions/41015311/picking-about-random-character-without-repetition-c) – izlin

+0

使用循序渐进的调试 –

回答

3

(目前循环将不若重复字符被发现终止。)但是,除了这个,代码讨厌的一对夫妇的其他原因:

  1. 你假设ASCII编码不是由标准的保证。

  2. 采样替换可能会导致循环问题,并且还可能产生统计异常(尽管像rand()这样的粗发生器不会比发生器本身更糟糕)。

一种解决方案是写

char s[] = {'a', 'b', 'c', .../*ToDo - type out all the other letters*/, 'z'}

使用

std::random_shuffle(std::begin(s), std::end(s)); 

洗牌这和读出的s前10个元素。

+0

你能解释为什么loop doesn发现重复时终止? – novice

+0

下面的答案(我upvoted)做。 – Bathsheba

1

一旦标志设置为2,它就会卡住。您应该在while循环内将标志重置为1。