remove character from char array,

hi
how can I remove a specific character from char array that entered by user ?
please help me :(

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
#include<iostream>
using namespace std;


int i=0;
const int size=100;
char array1[size];

void remove_char();//remove character

int main()
{

cout<<" enter text "<<endl;
gets(array1);
remove_char();

return 0;
}


void remove_char()
{
char c;
cout<<"Enter the character that u want to remove it ";
cin>>c;

//what can i do here to remove this character?

}

Check the cstring library. There is a utility to find characters. Removal you'll have to do yourself.
http://cplusplus.com/reference/clibrary/cstring/

But do note that strings are the superior method of containing... strings.
http://cplusplus.com/reference/string/string/find/
http://cplusplus.com/reference/string/string/erase/

-Albatross
Last edited on
closed account (Lv0f92yv)
Indeed strings are the way to go. If you must remove a character from an array, you'll probably have to do it the hard way - looping through it, find the character to remove, and move all characters after it down one, overriding the character and making the array one smaller.
I'd say let the function do it all. I mean up there u have a function that's called remove_char(), but think of what it does? It just asks for a character! So, you either change its name, to get_char(), or do make that function remove the character. Hint: after loading the array pass it to the function and let it find the match, or not.

Since it's an array of chars the way is to check each element against the character to be removed. That is a loop.

About loading the array: gets() is not a good idea; some might say gets() is evil!!! In this case
the string is 100 bytes of considerable length and probably suits your needs or the programs.The reason for gets() to be so infamous is that it may cause stack overflow, that's to write beyond the length of the array cuz there's no way to tell it how many characters should it read. There's another one: fgets() and it gets 3 args: the array, how many elements to store, and from where should it read 'em. Tou'll end up with: fgets(array, size, stdin) now if you don read the "size" elements, that's 100 up there, then before the null character that ends the string you'll get appended an '\n' newline character. I'll leave it to you to remove it!!!!
That's all C style, since you have included <iostream> consider using getline() read up on this there are 2 diferent versions.....
Character arrays are often inferior to strings, though gets() indeed is a poor idea. Try cin or getline.

-Albatross
Last edited on
Topic archived. No new replies allowed.