I have the following members in a struct
:
typedef struct rect RECTANGLE;
struct rect
{
char command[16];
int width;
int height;
int x;
int y;
};
i want to parse the following input string into above struct:
new 3,4+7,8
For now i have the following code:
printf("Command input? ");
scanf("%15[^,]%d,%d+%d,%d",
new_rect.command,
atoi(&new_rect.height),
atoi(&new_rect.width),
atoi(&new_rect.x),
atoi(&new_rect.y));
printf("Command: %i\n", new_rect.command);
printf("Height: %i\n", new_rect.height);
printf("Width: %i\n", new_rect.width);
printf("x: %i\n", new_rect.x);
printf("y: %i\n", new_rect.y);
The code's %15[^,]
will read up to the first comma, ie "new 3"
which isn't what you want. Also you need to read the comma which terminates %15[^,]
or the subsequent %d
will fail. And always check the return value from scanf()
which should have been 5
.
Assuming that the command is a single word, this code seems to do the job. There was also an error in %s
being %i
for a string in the first printf
#include <stdio.h>
struct rect
{
char command[16];
int width;
int height;
int x;
int y;
} new_rect;
int main(void){
if(scanf("%15s%d ,%d +%d ,%d", new_rect.command, &new_rect.height, &new_rect.width, &new_rect.x, &new_rect.y) == 5) {
printf("Command: %s\n", new_rect.command);
printf("Height: %i\n", new_rect.height);
printf("Width: %i\n", new_rect.width);
printf("x: %i\n", new_rect.x);
printf("y: %i\n", new_rect.y);
}
return 0;
}
If have added some extra spaces in the format string to make it more tolerant of spaces that might be input. That's not necessary before %d
, which filters whitespace anyway.
Running the program with the input shown gives
new 3,4+7,8
Command: new
Height: 3
Width: 4
x: 7
y: 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.