Monday, July 27, 2009

Taking String as input in C language?

hii everyone, i am in great need with this now. I want a string like " i love my nation" to be taken as a input. And i want every character of that string to be stored in a array. I want it as i have to display "e" in the whole string independently. I know that space is also counted while using strlen() function. Will it also be in array ?


It would be helpful if i get array elements as {i,l,o,v,e,m,y,n,a,t,i,o,n} only. Please help me out...

Taking String as input in C language?
In essence the answer to your question is yes.





I'm on linux and do most of my programming with gcc. I tend to use gets() for getting input, however I should warn you I always get the following message (apparently from the linker, ld):





/tmp/cc7UUZwf.o: In function `main':


sample.c:(.text+0x18): warning: the `gets' function is dangerous and should not be used.





The program always works. What happens is that I declare an array big enough to hold almost the traditional screen line of text, 80 characters. It should store 79 characters and assign '\0' to the last element. With gets, in stdio.h, I just type until I hit return. As soon as I hit return, everything I typed is put into the array I've designated EXCEPT the return which is replaced with a '\0' character, which terminates the string. Gets() doesn't check whether it will fit in my array. That's what makes it dangerous. Every space in my string is stored as a '\32' character, so it adds one to the strlen. You can take it out by creating another array and a pointer to an array, and using the pointer to copy every single character except " " to the second array. Make sure you copy to and copy the '\0' character. Unterminated strings are dangerous, vicious and evil things which open the doors to exploits and malware.





I know you'd love some code, but I think this explanation is the most important thing I can give you. I hope it helps.


No comments:

Post a Comment