-2

Hello? I want to know "how to convert char to string"

This is my C code

    string firSen;
    int comma1=0;
    cout<<"Please write your sentence"<<endl;
    getline(cin,first);
    int a=firSen.first("string");

    for(i=a;firSen[i] != ',';i++)
        comma1=i;
    cout<<firSen[comma1-3]<<firSen[comma1-2]<<firSen[comma1-1]<<endl;

I will write "The string is 100s, Thank you"

I know firSen[comma1-3]=1, firSen[comma1-2]=0, firSen[comma1-1]=0 for type of char.

And I want to put these char into string (Like 1,0,0 into string of 100) because I want to use atoi function....

Do you know how to convert char into string?

bluesky
  • 9
  • 1

2 Answers2

1

You can use std::istringstream instead of atoi. Something like this:

std::istringstream ss(firSen.substr(comma1-3)); int val; ss >> val;

FunkyCat
  • 448
  • 2
  • 6
1

In this case, if you know the location and length that you want, you can just extract a substring:

std::string number(firSen, comma1-3, 3);

and convert that to an integer type using the C++11 conversion functions:

int n = std::stoi(number);

or, historically, a string stream:

int n;
std::stringstream ss(number);
ss >> n;

or, if you want to be really old-school, the C library

int n = std::atoi(number.c_str());

There are other ways of building strings. You can initialise it from a list of characters:

std::string number {char1, char2, char3};

You can append characters and other strings:

std::string hello = "Hello";
hello += ',';
hello += ' ';
hello += "world!";

or use a string stream, which can also format numbers and other types:

std::stringstream sentence;
sentence << "The string is " << 100 << ", thank you.";
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644