Hello everyone ,
I have a function in my code which gets a string , sends it to another function for validation , and if the string
turns out to be invalid , then it calls the function again (which gets the string) .
I have made a simple code which demonstrates my question :
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[30];
short i;
scanf("%s",string);
if(strcmp(string,"1")==0)
main();
printf("%s",string);
}
Let us say that a valid string is all the strings which are not "1" .
If one enters three times "1" ("1", calls main() , "1" ,etc..) and then enters "2" , the output would be : "2111" .
My first thought was that the string wont re-initialize , so I have added a bit to my code which would put '\0' (end of string)
in each char :
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[30];
short i;
for(i=0;i<30;i++)
string[i]='\0';
scanf("%s",string);
if(strcmp(string,"1")==0)
main();
printf("%s",string);
}
As you can see - right after the declaration of the variable , I loop through each char and put '\0' in it ,
but the output stays the same ("2111") .
I have tried to replace the input/output functions , replace the manual loop to strcpy(string,"") , the output stays the same .
I`d really like to know what am I missing here , why wont the output just be "2" ?
Thank you much ,
Danny .