2009-03-05 70 views
2

我有下面的代碼片斷:無效轉換問題在C++

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*無效轉換遍歷字符串時?

回答

7

std::string operator []返回一個字符。字符串不能用一個字符實例化。

用途:

string base = string(1, tag1[j])代替

3

string tag1 = arg_vec [1];

tag1是一個字符串文字。

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

嘗試,char base = tag1[j];

4

將其更改爲

char base = tag1[j]; 
+0

但是這會與「base」內部發生衝突if(mutateNo <= 3) – neversaint 2009-03-05 05:24:25

+0

@foolishbrat:因爲OP選擇了錯誤的DNA類型,應該可能是vector(char),否? – dmckee 2009-03-05 05:26:38

1

一個問題是,錯誤消息說,這項計劃預計一個參數時,它實際上需要兩個。你或許應該遵循Unix的公約和顯示所需的使用過(或代替):

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

名稱「的argc」和「argv的」是非常傳統的(和我見過的唯一的主要選擇是「交流'和'av')。這可能值得堅持。

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 mentioned,你可以定義basechar因爲你不對其執行任何字符串操作反正。如果您決定這樣做,則需要將DNA更改爲vector<char>(並將DNA的初始化更改爲使用字符而不是字符串)。