随机数(rand)无法输出未知字符

时间:2016-09-03 03:51:09

标签: c++ random

我正在尝试创建一个nim游戏,我正在尝试生成游戏中使用的随机数,但它不起作用。这是我的代码:

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
string player1name,player2name,player1status,player2status,pile1,pile2,pile3;
int main(){
cout<<"What is player 1's name?"<<endl;
getline(cin, player1name);
cout<<"What is player 2's name?"<<endl;
getline(cin, player2name);
pile1 = rand() % 40 + 1;   
cout<<pile1;

return 0;
}

它成功编译,但其输出如下:

What is player 1's name?
Ttyeuo yuwew
What is player 2's name?
Yiefwh HYoaw
?
--------------------------------
Process exited after 15.84 seconds with return value 0
Press any key to continue . . .

因此随机数生成器无法正常运行,但我无法弄清楚它为什么会发生。有人可以帮我解决这个问题或建议一个更好的方法来生成随机数吗?

2 个答案:

答案 0 :(得分:3)

问题不在于rand()。问题是您将pile1声明为std::string,因此尝试将rand()的返回值分配给pile1,这将自rand() returns an int起无效

pile1更改为int,或将整数返回值转换为字符串:

int pile1;
//...
pile1 = rand%40 + 1;

Live Example 1

std::string pile1;
//...
pile1 = std::to_string(rand() % 40 + 1);

Live Example 2

此外,#include的正确std::string

#include <string>

而不是

#include <string.h>

答案 1 :(得分:1)

如果您将代码更改为此代码,则可能获得最佳结果:

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

int main(){
cout<<"What is player 1's name?"<<endl;
string player1name,player2name,player1status,player2status,pile1,pile2,pile3;
cin >> player1name;
cout<<"What is player 2's name?"<<endl;
cin >> player2name;
pile1 = rand() % 40 + 1;
cout << pile1;
return 0;
}