I have inputs similar to the following ones:
Johnhy ID5 409-208
I need to be able to read the input and to organize the output on a structure like:
Name: Johnhy
Type: ID5
ID Number: 409-208
But I'm struggling to find literature about how to handle the segment using the spaces. I'm pretty new to C, I confess.
CodePudding user response:
Declare the variables with appropriate lengths and:
scanf("%s %s %s", name, type, id);
CodePudding user response:
Look at this next bit if you want to see how to handle individual characters.
#include <stdio.h>
#include <string.h>
int main()
{
char mstring[] = "Hello World";
char space = ' ';
int a = 0;
while ( a < strlen(mstring))
{
if (mstring[a] == space)
{
printf ("found space!");
}
a ;
}
return 0;
}
Since my other answer wasn't acceptable, here is how to do it. But I think you'd learn a lot if you tried to write a function which returns each word based on the spaces. It depends on what you're trying to learn.
#include <stdio.h>
int main()
{
char mstring[] = "Johnhy ID5 409-208";
char name[50];
char type[50];
char id[50] ;
sscanf(mstring, "%s %s %s", name, type, id);
printf("Name:%s\nType:%s\nID:%s\n", name, type, id);
return 0;
}