c++ - C++中的无效转换问题

标签 c++ string char

我有以下片段:

string base= tag1[j];

这给出了无效的转换错误。

我下面的代码有什么问题?我怎样才能克服它。

完整代码在这里:

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <time.h>
using namespace std;


int main  ( int arg_count, char *arg_vec[] ) {
    if (arg_count < 3 ) {
        cerr << "expected one argument" << endl;
        return EXIT_FAILURE;
    }

    // Initialize Random Seed
    srand (time(NULL));

    string line;
    string tag1     = arg_vec[1];
    string tag2     = arg_vec[2];

    double SubsRate = 0.003;
    double nofTag   = static_cast<double>(atoi(arg_vec[3])); 

    vector <string> DNA;
      DNA.push_back("A");
      DNA.push_back("C");
      DNA.push_back("G");
      DNA.push_back("T");


      for (unsigned i=0; i < nofTag ; i++) {

          int toSub = rand() % 1000 + 1;

          if (toSub <= (SubsRate * 1000)) {
              // Mutate
              cout << toSub << " Sub" << endl;

              int mutateNo = 0;
              for (int j=0; j < tag1.size(); j++) {

                  mutateNo++;


                  string base = tag1[j]; // This fail

                  int dnaNo = rand() % 4;

                  if (mutateNo <= 3) {
                     // Mutation happen at most at 3 position
                        base = DNA[dnaNo];
                  }

                  cout << tag1[j] << " " << dnaNo << " " << base  <<  endl;
                  //cout << base;

              }
               cout << endl;

          }
          else {
              // Don't mutate
              //cout << tag1 << endl;
          }

      }
    return 0;
}

为什么在遍历字符串时会得到从 charconst char* 的无效转换?

最佳答案

std::string operator [] 返回单个字符。字符串不能用单个字符实例化。

使用:

string base = string( 1, tag1[j] ) 而不是

关于c++ - C++中的无效转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/613642/

相关文章:

c++ win32 在哪里画米

c++ - C++ 中的 cerr 和 cout 意外输出

.net - 为什么在 .NET 中复制字符串?

string - 如何检查一个字符是否是 Swift 中的空格字符?

c++ - 无正则表达式的字符串格式验证(C++03)

arrays - Kernighan 和 Ritchie 的主题 1.6

c++ - C++ 中的 int64 和 int64_t 有什么区别?

c - 查找 char 中的数字

将字符串数组复制到 C 中的另一个数组中

c++ - 二维 STL vector typeid