Reputation: 63984
I have the following snippet:
string base= tag1[j];
That gives the invalid conversion error.
What's wrong with my code below? How can I overcome it.
Full code is here:
#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;
}
Why do I get an Invalid conversion from char
to const char*
when looping over a string?
Upvotes: 2
Views: 1642
Reputation: 753455
One problem is that the error message says the program expects one argument when it actually requires two. You should probably follow the Unix conventions and show the required usage too (or instead):
if (arg_count != 3) {
cerr << "Usage: " << arg_vec[0] << " tag1 tag2";
return EXIT_FAILURE;
}
The names 'argc' and 'argv' are very conventional (and the only major alternative I've seen is 'ac' and 'av'). It might be worth sticking with that.
Upvotes: 1
Reputation: 340168
There is no constructor for string
that takes just a char
(which is what tag1[j]
is). You have a couple options:
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
or
string base( 1, tag1[j]); // create a string with a single char
Or as Josh mentioned, you can define base
as a char
since you're not performing any string operations on it anyway. If you decide to do this you'll need to change DNA
to be a vector<char>
(and change the initialization of DNA
to using chars instead of strings).
Upvotes: 2
Reputation: 29267
string tag1 = arg_vec[1];
tag1 is a string literal.
string base = tag1[j];
is initialized with a char
instead of char *
.
Try, char base = tag1[j];
Upvotes: 3
Reputation: 7799
The std::string operator []
returns a single char. string cannot be instantiated with a single char.
Use:
string base = string( 1, tag1[j] )
instead
Upvotes: 7