JP744
JP744

Reputation: 31

C++ test last character of a string

I want to test if the var string is terminated with a '\n' or not, in order to detect and remove some incomplete incoming variables from a stream async socket. It seems the following code doesn't work properly. Why ?

string var;
char *rest = nullptr;
char *pVar = nullptr;
istringstream iss(sReadBuffer); // Put into a stream            
while (getline(iss, var)) // Default delimiter '\n' or EOF
{                       
    int size = var.size();
    pVar = _strdup(var.c_str()); // Cast string to char * for later use (strstr,...)

    if(var[size] != '\n') // If incomplete variable found (not newline ended)...
    {
        debug("Incomplete variable found : ", pVar, "\n");
        rest = pVar;                                
        break;
    }

//... proceed with variable normally if they are complete

Upvotes: 1

Views: 2111

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

var[size] accesses the string out of bounds. But you can use the std::string::back member to get a reference to the last element.

if(var.back() != '\n')

That avoids potential indexing errors. The code above assumes var is not empty. You can check with std::string::empty(). For example,

if((!var.empty()) && (var.back() != '\n'))

How you expect to find a \n in a string read with getline is another matter.

Upvotes: 1

DrPizza
DrPizza

Reputation: 18340

getline() discards the newline. If you want to test for EOF, test the stringstream object itself.

Upvotes: 2

Related Questions