Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Character Between Strings in C++

Tags:

c++

string

So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

void converter(){
    converted = ":regional_indicator_" + character + ":";

}

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}


void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}
like image 704
jacksons123 Avatar asked Dec 01 '25 12:12

jacksons123


1 Answers

Append s behind the strings literals to treat them as std::strings instead of const char*s:

converted = ":regional_indicator_"s + character + ":"s;

You would need to do either using namespace std::literals or using namespace std::string_literals for it to work.

On a side note, in C++, it is strange to have a function converter() to modify a global variable using another global variable. You might want to consider passing character as a parameter to the function instead.

like image 194
Bernard Avatar answered Dec 03 '25 02:12

Bernard



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!