0

I'm trying to print the char. How do I convert the string to char? I get this error:

error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char' in assignment

#include <iostream>
#include <random>
#include <string>
#include <ctime>
using namespace std;
int const MAX = 4;

string randomString(int n){// generating random letter

    char alphabet[MAX] = { 'r', 'a', 'n', 'd'};

    string res = "";
    for (int i = 0; i < n; i++)
        res = res + alphabet[rand() % MAX];
 
    return res;
}

int main (){
    srand(time(NULL));
    char random;

    random = randomString(1);// problem lies here
    char a1 = random;

    char a2 = random;

    char a3 = random;
    cout<<a1<< " " << a2 << " " << a3<< endl;
}
2
  • 4
    randomString returns a std::string, random is a char. Commented Dec 16, 2021 at 18:38
  • 1
    std::__cxx11::string {aka std::__cxx11::basic_string} just means "std::string". Your error is "cannot convert 'std::string' to 'char' in assignment". Which is true. A std::string has no implicit conversion to char. Commented Dec 16, 2021 at 18:45

1 Answer 1

1

You appear to think that random is an alias for randomString(1) and that assigning random to multiple variables will call randomString(1) multiple times. It does not. That is not how variables work.

You are calling randomString(1) one time and then trying to assign its return value, which is a std::string (ie a collection of chars), to a single char. No such conversion exists, hence the error.

Try this instead:

int main (){
    srand(time(NULL));
    string a1 = randomString(1);
    string a2 = randomString(1);
    string a3 = randomString(1);
    cout << a1 << " " << a2 << " " << a3 << endl;
}

If you really want single chars, use std::string::operator[]:

int main (){
    srand(time(NULL));
    char a1 = randomString(1)[0];
    char a2 = randomString(1)[0];
    char a3 = randomString(1)[0];
    cout << a1 << " " << a2 << " " << a3 << endl;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.