【问题标题】:Storing Chars Into Strings in C++在 C++ 中将字符存储到字符串中
【发布时间】:2011-02-20 02:47:41
【问题描述】:

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

#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;
    }

}

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

【问题讨论】:

    标签: c++ arrays string variables chars


    【解决方案1】:

    只需添加

    string s(sLength, ' ');
    

    while (true)之前,改变

    cout << genRandom();
    

    s[x] = genRandom();
    

    在您的循环中,并删除 cout &lt;&lt; endl; 语句。这将通过将字符放入s 来替换所有打印。

    【讨论】:

    • 这工作除了字符串 s(sLength);它弹出一个错误。从 int 到 const char 的转换无效。
    • @Cistoran:我假设它像vector 一样工作(可以这样构造)。我会解决的。
    • 最好使用 s.reserve(sLength) - 这样您就不必将每个位置写两次。
    • @kotlinski:我正在使用[] 而不是push_back 编写元素,所以我需要resize 而不是reserve;我认为resize 也会写入所有元素。
    【解决方案2】:

    那么,这个怎么样?

        std::string s;
        for (int x = 0; x < sLength; x++)
        {
            s.push_back(genRandom());
        }
    

    【讨论】:

      【解决方案3】:
      #include<algorithm>
      #include<string>
      // ...
      
      int main()
      {
          srand(time(0));  // forget me not
          while(true) {
              cout << "What is the length of the string you wish to match?" << endl;
              cin >> sLength;
              string r(sLength, ' ');
              generate(r.begin(), r.end(), genRandom);
              cout << r << endl;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-24
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2012-08-22
        • 1970-01-01
        • 1970-01-01
        • 2018-12-01
        相关资源
        最近更新 更多