c++ - 在 C++ 中将字符存储到字符串中

标签 c++ arrays string variables chars

所以现在我有了这段代码,它可以根据用户输入确定的设定增量生成随机字母。

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int sLength = 0;
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";

int stringLength = sizeof(alphanum) - 1;

char genRandom()
{
    return alphanum[rand() % stringLength];
}

int main()
{
    cout << "What is the length of the string you wish to match?" << endl;
    cin >> sLength;
    while(true)
    {
        for (int x = 0; x < sLength; x++)
        {
            cout << genRandom();
        }
        cout << endl;
    }

}

我正在寻找一种方法来将第一个(用户定义的数量)字符存储到一个字符串中,我可以用它来与另一个字符串进行比较。任何帮助将不胜感激。

最佳答案

只需添加

string s(sLength, ' ');

之前while (true) , 改变

cout << genRandom();

s[x] = genRandom();

在你的循环中,删除 cout << endl;陈述。这将通过将字符放入 s 来替换所有打印.

关于c++ - 在 C++ 中将字符存储到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5054924/

相关文章:

c++ - 为什么我不能链接到 shaderc?

c++ - 如何从数组中并行删除零值

javascript - 在 javascript 参数中将单个字符视为字符串

javascript - Unix时间戳到秒数组indexOf

c++ - 将一段 C++ 代码包装成 Python

c++ - 这个 C++ while 循环是如何工作的?

javascript - 如何在 Javascript 中计算对象数组内的值?

C++ 摆脱空字符串行

java - 将时区名称转换为城市名称(删除大洲部分)

java - 如何用 HashMap 中的字符替换字符串?