Kyuu
Kyuu

Reputation: 1045

Storing a string of inputs into a struct in C

was wondering how I would be able to store a user inputted string in the format "string,character,integer,integer" into a struct. For example storing "apple,c,5,10" into

typedef struct {
char item[80];
char letter;
int x,y;
}information;

information apple;

I am trying to avoid going through using scanf and a long piece of code to make the comma into a delimiter so wondering if there was any other way to quickly read from scanf and chucking this information into the struct

Upvotes: 0

Views: 3608

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

You can use multiple format specifiers in the format string to scanf() to scan all the input at once, through a comma-seperated user input, like

int ret = -1;
if ((ret = scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y)) != 4)
                       //always check the return value of scanf()                       
{
   printf("scanf() failed\n");
   //do something to avoid usage of the member variables of "apple"
} 

However, I'll recommend the long way, like

  • read the line using fgets()
  • tokenize using strtok() and , as delimiter
  • use the token (or convert using strtol(), as required).

Much safe and robust.

Upvotes: 1

mtijanic
mtijanic

Reputation: 2902

You can specify complex formats using scanf, like:

scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y);

%79[^,] means scan anything that is not a comma character, up to 79 characters.

Note that this does no error handling if the user enters a poorly formatted string, like "aaa;b;1;2". For that, you'll need to write a lot more code. See strtok

Upvotes: 4

3wic
3wic

Reputation: 500

Try to read using the func read() then just split the string using strtok()

Here's some references :

strtok : http://man7.org/linux/man-pages/man3/strtok.3.html

read : http://linux.die.net/man/2/read

Upvotes: 0

Related Questions