Brendan Cameron Brendan Cameron - 1 year ago 82
C++ Question not comparing to character ' '

I am writing a C++ function that takes in a string of the form "let_varname_=_20" and then it will isolate "varname" to make a new string with my name variable name. I am trying to tell the .at() function to stop iterating through a while loop when it hits a space (the underscores are spaces, I just wanted it to be abundantly clear there was a space). However, it isn't comparing them properly, as it goes to the end of the string completely without stopping (passing by 2 spaces).

void store(std::string exp) {

int finalcount = 4;
char placeholder = ' ';
while (!=placeholder) {


for (int i = 0; i < exp.size(); i++) {
std::cout << << std::endl;

std::string varname = exp.substr(4, finalcount+1);

std::cout << finalcount + 1 << std::endl;
std::cout << varname << std::endl;


I started at index 4 because I know that indexes 0-3 of teh string will be 'l' 'e' 't' and ' '. The print statements were just me checking to see what it was reading versus what I input (and it was reading everything fine, just not comparing properly). I also tried have my while loop condition say while the char was >65 && <90 to work with ASCII codes but that also didn't work.

Thanks in advance for the help.

Answer Source

You could use istringstream and treat the string as a stream:

const std::string test_data = "let varname = 20";
std::istringstream test_stream(test_data);
std::string let_text;
std::string var_name;
char equals_sign;
unsigned int value;
test_stream >> let_text >> var_name >> equals_sign >> value;

This may be a lot easier than your code.

Edit 1: Searching the string
You could also use the std::string methods, find_first_of and find_first_not_of.

std::string::size_type position = test_data.find_first_of(' ');
position = test_data.find_first_not_of(' ', position);
std::string::size_type end_position = test_data.find_first_of(' ');
let_text = test_data.substr(position, end_position - position);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download