ctf*_*tfd 1 random objective-c++ c++03
我想将一个随机数与一些字母数字字符交错,例如:HELLO与随机数25635→混合H2E5L6L3O5.我知道%1d控制间距,虽然我不知道如何在随机数之间插入文本或如何实现这一点.
码:
int main(void) {
int i;
srand(time(NULL));
for (i = 1; i <= 10; i++) {
printf("%1d", 0 + (rand() % 10));
if (i % 5 == 0) {
printf("\n");
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句 - 如果我的随机数发生器不是很好,我愿意接受建议 - 谢谢
如果您对使用C++ 11没问题,可以使用以下内容:
#include <iostream>
#include <random>
#include <string>
int main() {
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<int> uniform_dist(0, 9);
std::string word = "HELLO";
for (auto ch : word) {
std::cout << ch << uniform_dist(e1);
}
std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)
...产生例如:
H3E6L6L1O5
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用旧的编译器,你可以使用rand和srand标准C库为您随机数:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
std::srand(std::time(NULL));
std::string word = "HELLO";
for (int i = 0; i < word.size(); ++i) {
std::cout << word[i] << (rand() % 10);
}
std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)