编写代码,C++生成随机字符串
时间: 2023-08-31 16:09:38 浏览: 68
可以使用rand()函数结合ASCII码生成随机字符。如下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LENGTH 10
int main()
{
srand(time(NULL));
char str[LENGTH+1];
for(int i=0; i<LENGTH; i++)
{
str[i] = rand() % 26 + 'a'; //生成小写字母
}
str[LENGTH] = '\0'; //字符串以'\0'结尾
printf("随机字符串为:%s\n", str);
return 0;
}
```
以上代码会生成10个随机的小写字母组成的字符串。
相关问题
随机生成字符串c++
可以使用C++的随机数生成函数和字符数组来生成随机字符串,示例代码如下:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
const int len = 10; // 字符串长度
char str[len+1]; // 字符串数组
srand(time(NULL)); // 初始化随机数种子
for (int i = 0; i < len; i++) {
str[i] = 'a' + rand() % 26; // 生成随机小写字母
}
str[len] = '\0'; // 字符串结尾
cout << str << endl; // 输出随机字符串
return 0;
}
```
vc6.0生成随机字符串
在VC6.0中生成随机字符串的方法有多种,以下是其中一种常见的方法:
1. 定义一个字符串变量存储随机字符串:
```c++
string str = "";
```
2. 定义一个随机数生成器,用于生成随机数:
```c++
srand((unsigned int)time(NULL)); // 初始化随机数发生器
```
3. 循环生成随机字符并添加到字符串中:
```c++
const int N = 10; // 定义生成随机串的长度
char c;
for (int i = 0; i < N; i++) {
c = rand() % 26 + 'a'; // 生成一个随机小写字母
str += c; // 将随机字符添加到字符串中
}
```
4. 最后输出随机字符串:
```c++
cout << str << endl;
```
完整代码如下:
```c++
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int main() {
srand((unsigned int)time(NULL)); // 初始化随机数发生器
const int N = 10; // 定义生成随机串的长度
string str = ""; // 定义字符串变量
char c;
for (int i = 0; i < N; i++) {
c = rand() % 26 + 'a'; // 生成一个随机小写字母
str += c; // 将随机字符添加到字符串中
}
cout << str << endl; // 输出随机字符串
return 0;
}
```