Rafael
Rafael

Reputation: 25

How to add a character in a predefined string?

I made a function that separates one of my data points to eliminate a character.I want to add R: G: B: into the 3 numbers. So for example if the values are 255,0,0 than it becomes

255
0
0

I want it to be

R:255
G:0
B:0

This is the function I made to separate the commas.

#include string
    void RGB(string input)
{
    istringstream ssString(input);

    while (getline(ssString, input, ','))
        cout<< input << endl;


}

Upvotes: 1

Views: 116

Answers (2)

Andria
Andria

Reputation: 5075

A way to do this without adding or subtracting lines from your code would be:

    int c = -1; // counter
    while(std::getline(ssString, input, ','))
        std::cout << (++c == 0 ? 'R' : c == 1 ? 'G' : 'B') << ": " << input << std::endl;
    return 0;

The ternary operator utilizes a counter variable that starts at -1, the ternary eliminates the need for several if statements. Note: you have to wrap the ternary in parenthesis ( ) otherwise the compiler throws errors at you.

Upvotes: 0

paddy
paddy

Reputation: 63471

You can just iterate through an array of your prefixes. Something like this would be sufficient.

const char *prefix[3] = { "R:", "G:", "B:" };
for( int p = 0; p < 3 && getline(ssString, input, ','); p++ )
{
    cout << prefix[p] << input << endl;
}

Upvotes: 2

Related Questions