Reputation: 33
I am quite new to programming in C and I have a problem that I have been trying to solve the last days, but now I am at a point where I don't know what to do.
I am reading in a string with the function "input" which gets then split into parts everytime there is a white space. The parts are stored in char arrays, which works fine so far. However, when I call the next function "checkInput" in main, the char arrays are empty again. What do I have to change, so that the char arrays are not empty when calling the next function?
When I used scanf instead of fgets, it worked. But why?
Any help would be much appreciated.
void input(char* string1, char* string2, char* string3)
{
char ptr[100];
printf("Enter String: \n");
fgets(ptr, 100, stdin);
printf("%s \n", ptr);
if(ptr != NULL)
{
string1 = strtok(ptr, " \n");
printf("string1: %s \n", string1);
}
if(ptr != NULL)
{
string2 = strtok(NULL, " \n");
printf("string2: %s \n", string2);
}
if(ptr != NULL)
{
string3 = strtok(NULL, " \n \0");
printf("string3: %s \n", string3);
}
}
int main(void)
{
char string1[100];
char string2[100];
char string3[100];
input(string1, string2, string3);
checkInput(string1, string2, string3);
return 0;
}
Upvotes: 2
Views: 69
Reputation: 84642
Since you declare string1, string2, string3
in main()
as arrays of 100 characters each with automatic storage duration, the storage is already provided for the arrays in input()
. The easiest thing to do to get the strings back in main()
and avoid the problem with storage for ptr
in input()
becoming invalid on return is simply to strcpy
the tokens to your strings in input()
, e.g.
void input(char* string1, char* string2, char* string3)
{
char ptr[100], *p = ptr;
printf ("Enter String: \n");
fgets (p, 100, stdin);
printf("%s \n", ptr);
if (p != NULL)
{
p = strtok (p, " \n");
if (p)
strcpy (string1, p);
printf("string1: %s \n", string1);
}
if (p != NULL)
{
p = strtok (NULL, " \n");
if (p)
strcpy (string2, p);
printf("string2: %s \n", string2);
}
if (p != NULL)
{
p = strtok (NULL, " \n \0");
if (p)
strcpy (string3, p);
printf("string3: %s \n", string3);
}
}
Now string1, string2
and string3
will remain valid until you exit main()
and your program is over.
Upvotes: 1