1

I'm trying to make a function that filters out all the punctuation and spaces in a sentences and returns only the letters and numbers in a new string.

ex. If I type: Hi, my name is Zach1234. I want it to return only: himynameiszach1234

Yet it it keeps returning only the first letter. Any ideas on how to remedy this problem?

#include <iostream>
#include <cctype>
using namespace std;

string filter(string str)
{
    string result = "";
    for(int i = 0; i < (str.size()-1); i++)
    {
        if(isspace(str[i]))continue;
        if(ispunct(str[i]))continue;
        if(isdigit(str[i]))result += str[i];
        if(isalpha(str[i]))result += str[i];
    }
    return(result);
}


int main()
{
    string happy;

    cout <<"Please enter a string\n";
    cin >> happy;

    cout << filter(happy) << endl;

    return(0);
}
2
  • 1
    First off you should be using getline() to read in input with spaces. Commented Jul 22, 2015 at 0:08
  • @NathanOliver that's exactly the issue, you should post an answer Commented Jul 22, 2015 at 0:12

4 Answers 4

1

The problem is that cin >> happy; is not reading in all of your input. The >> operator will stop at the first white space character it reads and leave that in the stream. Instead you need to use std::getline().

std::getline(std::cin, happy)

This will store the contents from the stream into happy until it reaches a newline or the end of file. If it does read in a newline then it is not added to the string but it is discarded. You do need to take care when mixing >> and `getline() though: Need help with getline()

As mentioned by user5141375 your for loop is also incorect. size() returns the number of characters in the string so you need to loop to i < str.size() and not i < str.size() - 1

Sign up to request clarification or add additional context in comments.

Comments

1
cin >> happy;

This code read a string from your input until get a space, so if you type:

Hi, my name is Zach1234

You will get:

Hi;

For this loop,

for(int i = 0; i < (str.size()-1); i++)

the condition should be: i < str.size() or i <= str.size() - 1

2 Comments

Please use i < str.size() - it's more idiomatic than i <= str.size() - 1. A <= in a for loop test is something that always requires extra examination. For example, in this case it will cause a problem when str.size() happens to be 0.
Hey, as you can see, I edited your answer to make it a lot more readable. In the future, you should take full advantage of SO's formatting features to make better and more readable answers.
0

Problem solved. I should have been using getline() instead of cin.

Comments

0

You could also use isalnum() for your filter function to consolidate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.