1

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; } 
3
  • Keep track of which line you're reading and append R, G or B accordingly. Also try and use const string& input in your signature, it helps avoid unnecessary copying. Commented Apr 6, 2017 at 1:34
  • What exactly is your problem? Commented Apr 6, 2017 at 1:35
  • @tadman I have tried to do that but since its in a while loop it just repeats those characters, so if I only had to do R: I would be fine but every iteration has to be different and I don't know how to implement that. Commented Apr 6, 2017 at 1:41

2 Answers 2

2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help.
0

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.

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.