How to read a txt file into an array

This is a discussion on How to read a txt file into an array within the C Programming forums, part of the General Programming Boards category; Originally Posted by Hitsugaya_KK I am now getting an error based on "char retstr, [BUFSIZ];" . It is saying Error ...

  1. #31
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,461
    Quote Originally Posted by Hitsugaya_KK
    I am now getting an error based on "char retstr, [BUFSIZ];" . It is saying Error 2 error C2059: syntax error : '['
    Post your current code, including the headers included.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #32
    Banned
    Join Date
    Aug 2009
    Posts
    30
    Code:
    #include <stdio.h> 
    #include <string.h>
    #include <sys/types.h>
    #include <stdio.h>
    
    
    struct item
    {
               int ID;
               char name[64];
               int price;
    };
    int main(int argc, char *argv[])
    {
               FILE *fp;
               char retstr[BUFSIZ];
               int *f1;
    	   char *f2; 
    	   int *f3;
    	   char *p;
               int max_cnt=15;
               int i, cnt=0;
    
          	   struct item record [10];
    	  
    	 
    	       if (fp=fopen("C://shoppinglist.txt","r"));
    	       {
               printf("Error: can't open file.\n");
    		   }
    		   if( fp != NULL ) 
               {
               
               while( fgets(retstr, BUFSIZ, fp) != NULL )
               {
    
    	       if ((p = strchr(retstr, '\n')) != NULL)
    	       *p = '\0';
    	       if(cnt == max_cnt)
    	       break;
    
    	       f1=strtok(NULL, " ");
    	       f2=strtok(retstr, " ");
    	       f3=strtok(NULL, " ");
    	       strcpy(record[cnt].ID, f1);
    	       strcpy(record[cnt].name, f2);
    	       strcpy(record[cnt].price, f3);
    	       
    
    	       cnt++;
               }
    
    
    
    
    	       
               exit(1);
               }
    	
    
    
               for(i=0; i < cnt; i++)
               {
    
    
               printf("%d %s %d %d\n", record[i].ID, record[i].name,record[i].price,record[i].quantity);
      
               }
    
               fclose(fp);
    
     
               exit(0);
    }
    I was able to get read of the error by remobing "char retstr,[BUFFSIZ]; since it had already been initialized.

    this is the next seop:
    Code:
    {
    Int option;
    int a; /*it lists all the items*/
    int b; /* it looks for the item with the lowest price*/
    int c; /* it discounts 20% of the price from all items only once*/
    int d:/* it allows the user to select the items he wants and customise the quantity of each item*/
    
    printf( "1 - view the complete list of goods in the shop, with their prices" );
    printf( "2 – list the cheapest item on offer" );
    printf( "3 – “discount” option" );
    printf( "4 – choose items for purchase" );
    printf( "5 – total price for items" );
    printf( "6 - Exit");
    
    switch ( option ) {
    case 1:
    case 2:
        break;
    case 3:
    case 4:
        printf( "choose item for purchase\n" );
        break;
    case 5:
        printf( "total price for items\n" );
        break;
    case 6:
        printf( "Exit\n" );
    }
    
    return 0;
    Last edited by Hitsugaya_KK; 08-19-2009 at 08:42 AM.

  3. #33
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I can only go so far in the second part

    Code:
    int menu_choice;
    
    
    
    switch ( menu_choice) 
                {
                case 1: 
    	                   for(i=0; i < cnt; i++) 	
    	                   { 
    
                               printf ("%d %s %d\n", record[i].ID, record[i].name,record[i].price); 
    	
    	                   }
    
                  case 2:    
                              cheapest item = record[i].price
    	                   for(i=0; i < cnt; i++)
    	                   {
    		 
                               if (record[i].price < cheapest item)
    	                   
             	           cheapest item = record[]i.name,record[i].price
                               }
     
                  case 3:
    	                   int discount = (record[i].price)x ((float)0.2 x (record[i].price)) 
       
    		            for(i=0; i < cnt; i++)
    				 
                               {
    			    
                               printf("%s %d\n",record[i].name,discount);
    
                               }			
    
                 case 4:       printf( "choose item for purchase\n" );
                                   break;
            
    
                 case 5:       printf( "total price for items\n" );
                                     break;
                    
                 case 6:       printf( "Exit\n" );
                 }
    
    return 0;
    }
    can someone help me with the option 4?
    Last edited by Hitsugaya_KK; 08-19-2009 at 10:16 AM.

  4. #34
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Your braces dont have matching end braces.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  5. #35
    Banned
    Join Date
    Aug 2009
    Posts
    30
    do you have any idea how I can code option 4?

  6. #36
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by Hitsugaya_KK View Post
    do you have any idea how I can code option 4?
    Ask them for an item, then put the associated item and quantity into an "order" (what an "order" actually is, is up to you to decide).

  7. #37
    Banned
    Join Date
    Aug 2009
    Posts
    30
    but I don't know how to make the user choose the item or even quantity. I know I have to use the integer ID from the array to allow the user choose, the question is how to code it.

  8. #38
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    but I don't know how to make the user choose the item or even quantity. I know I have to use the integer ID from the array to allow the user choose, the question is how to code it.
    Don't use the ID number. Print the array like a menu using a loop, and add an option number corresponding to the array index:
    Code:
    for (i=0;i<10;i++) print("choice %d - %s\n",i+1,array.name);
    So the number entered by the user equals the array index of the item (+1, if you don't want to start with 0). These may end up being the same as the ID numbers -- but maybe not if you have sorted the array using some other criteria (eg, alphabetically). This way you do not have to search the array for anything.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #39
    Banned
    Join Date
    Aug 2009
    Posts
    30
    Code:
    case 4: printf( "choose item for purchase\n" );
                 for (i=0;i<10;i++)
                {
    					  
    	     printf("choice %d - %s\n",i+1,array.name);
    
    	      }
    Now the question is, how do I request the user to input the index with the aid of a scanf function?

  10. #40
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    Now the question is, how do I request the user to input the index with the aid of a scanf function?
    scanf() is pretty straightforward but it has lots of little quirks. I recommend you write a short test program that you can keep separate from your projects and you can use that when you need to figure something out about scanf() -- this is much easier than doing it in your developing code and will save you time in the long run. I have directories full of short test things like this that I refer to and screw around with I need to figure out how something has to be done.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    /* scanf() testing */
    
    int main(void) {
    	int i, x[3];
    	for (i=0; i<3; i++) {
    		printf("\nEnter a number: ");
    		scanf("%d",&x[i]);
    	}
    	printf("\nYou entered %d %d %d\n",x[0],x[1],x[2]);	
    	return 0;
    }
    Also: Don't write all this into the switch/case block. Use the switch to call functions which do the work and return relevant values. Otherwise you will end up with an overly long and awkward main() which does everything. Functions exist for a reason. Use them. Write them. Based on your specs, I would say you should have the one switch/case in main() and every single option should call a separate function.
    Last edited by MK27; 08-19-2009 at 03:45 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #41
    Banned
    Join Date
    Aug 2009
    Posts
    30
    Choosing the quantity for each of the items will make it harder to code. The number of items the person would like to choose should be up to 10 and the person should be able to stop choosing items at anytime during the process. Was thinking maybe there should be a confirmation option for if someone wants more items or not.

  12. #42
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    Choosing the quantity for each of the items will make it harder to code. The number of items the person would like to choose should be up to 10 and the person should be able to stop choosing items at anytime during the process. Was thinking maybe there should be a confirmation option for if someone wants more items or not.
    Part of the reason putting stuff in a function helps is that using functions add a level of "functionality". So for example you could have a loop in the case: block that calls the choosing function (and the choosing function returns the item chosen) with the confirmation option at the end of the loop to possibly break the loop.

    Code:
    	int x=0;
    	while (x!=666) {
    		printf("\nEnter a number: ");
    		scanf("%d",&x);
    	}
    This will just repeating until you enter 666. So (to reiterate), you can use something like that in the case statement to call the choosing function, and then ask the user if they want to choose again.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #43
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I have done this so far

    Code:
                     case 4: printf( "choose item for purchase\n" );
    			      int i, x[10],int quantity;
    			      for (i=0;i<10;i++)
    				  
    	                  {
    		          printf("Enter a number: ");
    				  
    		          scanf("%d",&x[i]);
    	                  }
    
    			  {
    		           printf("Enter quantity for item\n")
    		           scanf("%d",&quantity[i]);
    		           }
    
    			    printf("Do you want to choose more items? Yes[1] No[2]")
    				  
    
    
    	                    printf("You entered %d %d %d\n",x[0],x[1],x[2]);	
    
    				   
    	                    return 0;
    }
    I need help in implementing some of the functions.

    I don't know if this will still help :

    Code:
    	  printf("choice %d - %s\n",i+1,array.name);

  14. #44
    Banned
    Join Date
    Aug 2009
    Posts
    30
    Code:
    #include <stdio.h> 
    #include <string.h>
    #include <sys/types.h>
    #include <stdio.h>
    
    
    struct item
    {
               int ID;
               char name[64];
               int price;
    };
    int main(int argc, char *argv[])
    {
               FILE *fp;
               char retstr[BUFSIZ];
               int *f1;
    		   char *f2; 
    		   int *f3;
    		   char *p;
               int max_cnt=15;
               int i, cnt=0;
    		   int menu_choice;
    		   int cheapest_item;
    		   int discount;
    		   int x;
    		   int quantity;
    
          	   struct item record [10];
    	  
    	 
    	       fp=fopen("C://shoppinglist.txt","r");
    		   
    		   if(fp==NULL)
    	       {
               printf("Error: can't open file.\n");
    		   
    		   exit(1);
    		   }
    
    
    		   
               
    		   while( fgets(retstr, BUFSIZ, fp) != NULL )
               {
    
    	       if ((p = strchr(retstr, '\n')) != NULL)
    	       *p = '\0';
    	       if(cnt == max_cnt)
    	       break;
    
    		   f1=strtok(retstr, " ");
    	       f2=strtok(NULL, " ");
    	       f3=strtok(NULL, " ");
    	       strcpy(record[cnt].ID, f1);
    	       strcpy(record[cnt].name, f2);
    	       strcpy(record[cnt].price, f3);
    
    	       cnt++;
               }
    
             
    
    
    
    
    
    
    
              scanf("%d",&menu_choice);
    
    		  switch (menu_choice){ 
              
              case 1: 
    	            for(i=0; i < cnt; i++) 	
    	            { 
    
                    printf("%d %s %d\n", record[i].ID, record[i].name,record[i].price); 
    	
    	
                 	}
    				break;
    
             case 2:    
                    cheapest_item = record[i].price;
    	            for(i=0; i < cnt; i++)
    	            {
    		
                    if (record[i].price < cheapest_item)
    	            {
           	        printf("%s %d\n",record[i].name,record[i].price);
    				}
    				
    				break;
    
             case 3:
    			       discount = (record[i].price) - ((float)0.2(record[i].price)); 
    
    				   for(i=0; i<cnt; i++)
    				   {
    			       printf("%s %d\n",record[i].name,discount);
    				   }
    				   break;
    
    			
    
              case 4: 
    			      {
    			      printf( "choose item for purchase\n" );
    				  }
    			      for (i=0;i<10;i++)
    				  
    	              {
    		          printf("Enter a number: ");
    				  
    		          scanf("%d",&x[i]);
    	              }
    
    				  {
    				  printf("Enter quantity for item\n");
    				  scanf("%d",&quantity[i]);
    				  }
    
    				  {
    				  printf("Do you want to choose more items? Yes[1] No[2]");
    				  }
    
    				  {
    	              printf("You entered %d %d %d\n",x[0],x[1],x[2]);	
    				  }
    				   
    	             
    
    				  {	  
    				  printf("choice %d - %s\n",i+1,record[i].name);
    				  }
    
                      break;
                      
    		          case 5:
    				  {
                      printf( "total price for items\n" );
    				  }                   
    				  break;
                      
    				  case 6:
    				  {
                      printf( "Exit\n" );
                      }
    				  break;
    
    
          
               fclose(fp);
               exit(0);
    }
    my whole code, but having some problems with case 4

  15. #45
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    x is an int, as is quantity, but in this part of your code, you're treating them like they're arrays.


    Code:
    		          printf("Enter a number: ");
    				  
    		          scanf("%d",&x[i]);
    	              }
    
    				  {
    				  printf("Enter quantity for item\n");
    				  scanf("%d",&quantity[i]);
    				  }
    
    				  {
    				  printf("Do you want to choose more items? Yes[1] No[2]");
    				  }
    
    				  {
    	              printf("You entered %d %d %d\n",x[0],x[1],x[2]);	
    				  }
    Your code is maddening to read through because of it's indentation style. Please find and follow
    either a student/business style, or K & R style.

    You do NOT need all those bloody curly braces, around every single line of your code!!
    Curly braces go around everything in a function, and also surround any multiple line statements,
    in a block of code. THAT IS ALL.

    example:
    Code:
    if(you want more people to read your code, and your program to be better)
    {
       use a decent indentation style
       more people will read it
       more people will assist you with it
       you will see more bugs, more easily, using this style
       others will see the bugs in your code easier as well
    }
    
    Because this if statement shows multiple dependent lines of "code" for it, it needs 
    curly braces around them. Without them, only the first line of code would be 
    part of the if statement.
    You should be getting plenty of errors and warnings from your compiler. If you are not, then please adjust your
    warning and error level for your compiler.
    Last edited by Adak; 08-20-2009 at 12:40 PM.

Page 3 of 4 FirstFirst 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21