Filter string function problem

I'm in a beginners class in C++ and so far we've only gotten through 5 chapters in our book. We have homework every night and it's usually very easy, well this one is stumping me and I have no idea where to go with it.

I'm supposed to take a string (ex: Do geese see god?) and filter it into (Dogeeseseegod). So far I haven't been able to get the second part, but I know I'm close to a solution.

Does anyone have any fixes for my code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<string>
using namespace std;

string filter(string s)
{
  int x = s.size();
  for(int i = 0; i <= x; i++)
  {
    if(isalpha(i))
    {
      cout << (char)i;
    }
  }
  return s;
}


int main()
{
  string s;
  
  cout << "Enter a string: ";
  getline(cin, s);

  cout << "Filtered string is: ";
  filter(s);
  

  return 0;
}
Last edited on
line 8 - the elements will run from 0 to x-1 so i = x will be out of bounds

line 10, 12 - you're checking the index number itself - I think you want to check the ith element e.g. s[i] ?

line 5, 15 - you're doing the output in the function, so it doesn't seem like you need to return anything from it
I've fixed the out of bounds and just made it "for (int i = 0; i < x; i++).
If I'm supposed to change it for lines 10, 12 what should the if statement look like? Or should I have one there at all?
1
2
3
4
if(isalpha(s[i])) // check the ith element of the string, not the value of i itself
    {
      cout << s[i]; //output the value of that element 
    }
HUZZA! It works! Thank you so much! You have no idea how long I've been stuck on this! You're amazing.
Topic archived. No new replies allowed.