我有以下片段:
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*
的无效转换?
最佳答案
std::string operator []
返回单个字符。字符串不能用单个字符实例化。
使用:
string base = string( 1, tag1[j] )
而不是
关于c++ - C++中的无效转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/613642/