Solved

Using fgets() and sscanf

Posted on 2003-12-02
6
2,300 Views
Last Modified: 2008-02-01
Hi I am trying to enter data into some structs dynamically.

My code is as follows

#include <stdio.h>

struct node {
      int data;
      char object[25];      
      struct node *next_ptr;
      };

int main() {
 
      struct node *node_1, *node_2;
      char buffer[255];
      char *new_object;
      
      node_1 = (struct node*)malloc (sizeof(struct node));
      node_2 = (struct node*)malloc (sizeof(struct node));
      
      node_1->next_ptr = node_2;
      node_1->data = 3;
      node_2->next_ptr = node_1;
      node_2->data = 4;                
 
      printf("Please Enter An Object \n");
      new_object = fgets(buffer, 255, stdin);
      printf("You have entered: %s\n", new_object);
            
      //n_obj = sscanf(new_object);
      node_1->object = new_object;
      
            
      printf("Data: %d\n", node_1->data);
      printf("Object You entered into struct is: %s ?\n", node_1->object);
      return (0);
      }


I want the user to enter input in the command line then I want to be able to store this in the appropriate part of my struct.
I am using fgets() to grab the input from the command line, but my problem now is how to enter that into the struct,
I can print it out directly to check that my program has got the data and it has.
I have read that sscanf() can be used to extract data from fgets() but I cant find much info on google.

At the moment i get this compiling error
 gcc test.c -o testb
test.c: In function `main':
test.c:24: warning: assignment makes integer from pointer without a cast

Also do i need to flush out my       char buffer[255];
in order for me to be able to do another fgets()??

Thanks
0
Comment
Question by:welsh_boy
  • 4
6 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9857421
> am using fgets() to grab the input from the command line, but my problem now is how to enter that into the struct,
you can read the data directly into the structs .... this will save the overhead of parsing buffer after fgets() and assigning data to structs

>//n_obj = sscanf(new_object);
 int sscanf( const char *str, const char *format, ...);

as you can see sscanf returns an int which you are assigning to a char * n_obj ... hence the error ...

to read values into struct using sscanf, use

sscanf ( buffer, "%d %s", node1->data, node1->object );

where node1 is struct * (with enough memory allocated)
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9857437
>Also do i need to flush out my      char buffer[255];
>in order for me to be able to do another fgets()??
not necessary .... just be careful when your input ends ... you can use fgets in a loop like this

while ( fgets ( buffer, MAX_BUFFER, file_pointer ) != NULL )
{
              //process buffer
}
this will read information into buffer in successive iterations and process that buffer...
The loop will terminate when EOF is encountered
0
 

Author Comment

by:welsh_boy
ID: 9857505
Thanks sunnycoder sscanf does indeed input it straight to the struct.

At the moment I am only processing inputs from the command line:  -

      printf("Please Enter An Object \n");
      new_object = fgets(buffer, 255, stdin);
      printf("You have entered: %s\n", new_object);
            

        sscanf ( buffer, "%s", node_1->object );
      
      printf("Please Enter A Question \n");            
      new_object = fgets(buffer, 255, stdin);      
        sscanf ( buffer, "%s", node_1->question );      
            

      printf("Object You entered into struct is: %s \n", node_1->object);
      printf("Question You entered into struct is: %s \n", node_1->question);

This seems to work fine apart from it only processes the first word passed in the command window, e.g If i input the question  ; Is It big? it only processes "Is". I was using fgets() before to handle multiple words.

Also how should I go about setting the size of my buffer to correspond with the size of the string the user passes it.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 45

Expert Comment

by:sunnycoder
ID: 9857576
>This seems to work fine apart from it only processes the first word passed in the command window, e.g If i input the
>question  ; Is It big? it only processes "Is". I was using fgets() before to handle multiple words.
that is because scnaf breaks at whitespace and whitespace in C means blank, tab and newline ... to process blanks use

sscanf ( buffer, "%[^\n]s", node_1->question );
this will accpet string until a newline is encountered

> should I go about setting the size of my buffer to correspond with the size of the string the user passes it.
If you meant size of buffer used in fgets, then I am afraid there is no way to do that ... you declare the buffer before you start reading in ... If however you meant size of elements of node1 etc., then,
declare them as char * and not char []
use strlen() on buffer to determine the length entered
malloc() that may bytes and store their address in the char *

>Thanks sunnycoder sscanf does indeed input it straight to the struct.
Welcome ... what I actually meant was using something like this

     printf("Please Enter An Object \n");
     scanf ( "%s", node_1->object );

No fgets() ... scanf() straight into the struct ... same format specifier %[^\n]s can be used here too to read in blanks
0
 
LVL 2

Accepted Solution

by:
colmcc earned 350 total points
ID: 9857734
Note that the following line is not valid.-

node_1->object = new_object;

I'm surprised the compiler allowed this.
node_1->object is a char buffer.  You can't assign a pointer to it.  You would need to copy the chars using memcpy() or strcpy().  Although, as has been said, you can cut out the middle man and read your text straight into the desired buffer.

You didn't mention wanting to populate the 'data' field from the file, as well as the 'object' field.  But if you do, then there is a '&' missing from sunnycoder's example code. (sscanf needs the address of the field).  You would need -

sscanf ( buffer, "%d %s", &(node1->data), node1->object );

Regards,
Colin
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9857746
>But if you do, then there is a '&' missing from sunnycoder's example code. (sscanf needs the address of the field).  You would
>need
thanks for pointing out the error
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now