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);
}
Zach Stow
  • 157
  • 1
  • 11

4 Answers4

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

yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • 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. – Michael Burr Jul 22 '15 at 00:24
  • 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. – yizzlez Jul 22 '15 at 00:28
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

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

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

Zach Stow
  • 157
  • 1
  • 11
0

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

Marvin
  • 1
  • 1