Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid Conversion Problem in C++

Tags:

c++

string

char

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?

like image 533
neversaint Avatar asked Dec 13 '25 20:12

neversaint


1 Answers

The std::string operator [] returns a single char. string cannot be instantiated with a single char.

Use:

string base = string( 1, tag1[j] ) instead

like image 94
Gregor Brandt Avatar answered Dec 15 '25 10:12

Gregor Brandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!