简体   繁体   中英

Can i convert char symbol to string

Is there way to convert the symbol that char displays when you run the program like how 97 char is equal to "a" when you run the program into a string?

#include <iostream>
#include <ctime>
#include <windows.h>
#include <random>
#include <string>


using namespace std;

int main()
{
int max = 122, min = 97;
int range = max - min + 1;
srand (time(0));
char letter = rand() % range + min;
cout << letter << endl;
string letter2;
cin >> letter2;
if(letter2 == letter)
{
cout << letter2 << endl;
}
}

This is the code I tried but it didn't work. Thanks in advance.

First of all you could use an object of type std::string as letter. for example

std::string letter( 1, rand() % range + min );

Secondly you could use a character array as for example

char letter[2] = { char( rand() % range + min ), '\0' };

Or you could leave as is but the condition could look like

if ( letter2.size() == 1 && letter2[0] == letter )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM