2

我有以下片段:

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

为什么在循环字符串时会得到无效的char转换?const char*

4

5 回答 5

7

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

采用:

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

于 2009-03-05T05:24:09.357 回答
4

将其更改为

char base = tag1[j];
于 2009-03-05T05:22:36.443 回答
3

字符串 tag1 = arg_vec[1];

tag1 是一个字符串文字。

string base = tag1[j];用 achar而不是初始化char *

尝试,char base = tag1[j];

于 2009-03-05T05:21:50.720 回答
2

没有构造函数string只需要一个char(就是这样tag1[j])。你有几个选择:

string base;  // construct a default string
base  = tag1[j]; // set it to a char (there is an 
                 //   assignment from char to string, 
                 //   even if there's no constructor

或者

string base( 1, tag1[j]);  // create a string with a single char 

或者正如Josh 提到的那样,您可以定义base为 a char,因为无论如何您都没有对其执行任何字符串操作。如果您决定这样做,则需要更改DNA为 a vector<char>(并将初始化更改DNA为使用字符而不是字符串)。

于 2009-03-05T05:25:44.067 回答
1

一个问题是错误消息说程序需要一个参数,而实际上它需要两个参数。您可能应该遵循 Unix 约定并显示所需的用法(或相反):

if (arg_count != 3) {
    cerr << "Usage: " << arg_vec[0] << " tag1 tag2";
    return EXIT_FAILURE;
}

'argc' 和 'argv' 的名称非常传统(我见过的唯一主要替代品是 'ac' 和 'av')。可能值得坚持下去。

于 2009-03-05T05:23:00.233 回答