Zach Stow
Zach Stow

Reputation: 157

function isn't returning the desired string

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);
}

Upvotes: 1

Views: 75

Answers (4)

Marvin
Marvin

Reputation: 1

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

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180650

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

Upvotes: 1

user5141375
user5141375

Reputation: 11

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

Upvotes: 1

Zach Stow
Zach Stow

Reputation: 157

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

Upvotes: 0

Related Questions