0

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

1
  • C is a low level language and is generally not type safe like Python and many others. You have to do it the hard way or your life will be miserable because of the opportunities for errors like data validation, buffer overruns, etc. :( Commented May 12, 2015 at 13:23

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.