iverson
iverson

Reputation: 1083

How to terminate a std::string in C++?

I'm trying to remove all punctuation characters from a std::string in C++. My current code:

string str_in;
string::size_type i, j;

cout << "please input string with punctuation character..." << endl;
cin >> str_in;

for (i = 0, j = 0; i != str_in.size(); ++i)
    if (!ispunct(str_in[i]))
         str_in[j++] = str_in[i];

str_in[j] = '\0';

cout << str_in << endl;

Is str_in[j] = '\0'; wrong?

Upvotes: 3

Views: 991

Answers (4)

Soren
Soren

Reputation: 14688

the C++ string type is NOT implemented to be null terminated (although a c_str() call will give you a null terminated string.)

So yes, str_in[j] = '\0' is wrong for at least two reasons:

  1. The str_in.length() will not reflect the size of the string you expect with the punctuation removed.
  2. The null charatcter is an extra charter which will be sent to any output stream,
    such as cout << str_in;

Using the std::string class you should probably not oveeride the same buffer, but probably use a str_out buffer instead which will have the right length after you copy all the wanted (i.e. excluding the punctuation character), OR you should instead adjust the length of the str_in instead of adding the null.

Upvotes: 1

Blastfurnace
Blastfurnace

Reputation: 18652

If you want to truncate str_in to the first j characters, you can say str_in.resize(j).

If you want to use the standard library you could apply the erase-remove idiom like this:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string str_in;
    std::getline(std::cin, str_in);

    // Here is where the magic happens...
    str_in.erase(std::remove_if(str_in.begin(), str_in.end(), ::ispunct), str_in.end());

    std::cout << str_in << '\n';

    return 0;
}

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409196

Instead of modifying the same string, create a new string (e.g. str_out) and append to that:

str_out += str_in[i];

Upvotes: 0

RolandXu
RolandXu

Reputation: 3678

I think str_in[j] = '\0' is wrong when the string has no any punctuation.

Upvotes: 0

Related Questions