lycon
lycon

Reputation: 37

problem reconstructing a string removing punctuation

I am trying to write a program to strip the punctuation from a string. The input to the program should be a string of characters including punctuation; the output should be a string in which the punctuation is removed. I am using Visual Studio 2008 to compile and run the program. While executing it I am getting exception: "Debug Assertion Failed, Expression: string subscript out of range."

What am I doing wrong here?

int main()
{    
    string input;
    string output;

    getline(cin, input);

    string::size_type i = 0;
    for (string::size_type ix = 0; ix != input.size(); ++ix)
    {

        if (!ispunct(input[ix]))
        {
            output[i] = input[ix];
            ++i;
        }

    }


    cout << output << endl;

    return 0;
}

Upvotes: 0

Views: 513

Answers (4)

Loki Astari
Loki Astari

Reputation: 264411

Try the standard algorithms:

#include <string>
#include <iostream>
#include <cctype>
#include <functional>

int main()
{
    std::string input;
    std::string output;

    std::getline(std::cin, input);

    // This method copies items from the input container to the output container.
    // Unless the predicate is true (for the character being tested.
    // http://www.sgi.com/tech/stl/remove_copy_if.html
    std::remove_copy_if(input.begin(), input.end(),            // Input container
                        std::back_inserter(output),            // Output (note the back inserter)
                        std::ptr_fun<int, int>(&std::ispunct)  // a function that tests for punct.
                       );

    std::cout << output << "\n";
}

Unlike the original code (which does not allocate space for output), this uses the std::back_inserter iterator to push_back() new elements into the output container (thus automatically generating the space required).

Upvotes: 2

Mark B
Mark B

Reputation: 96241

You never allocated any space for the output string. Effectively, you're telling it to write into undefined memory locations, causing the assertion.

I can't tell if you want to remove the punctuation completely or just change it to say space, but assuming you want to remove it completely use this inside your if check:

output.push_back(input[ix]);

Upvotes: 2

Puppy
Puppy

Reputation: 146930

You did not set a meaningful size to the output variable, so you are accessing elements that do not exist. You need to output.push_back(input[ix]);

Upvotes: 4

Erik
Erik

Reputation: 91270

Use this:

output += input[ix];

output is empty - output[i] is trying to access outside output's bounds. std::string will not automatically resize if you try to access out of bounds.

Upvotes: 1

Related Questions