Hi,

I'm writing a program where the user can enters numbers and these numbers are stored in a file, then the numbers are read from the file and a certain calculation is done to each number by creating a thread for each

My problem is:
The first problem is whenever I enter a number with more the one digit the program won't read it and will terminate, here are the functions I'm using

/*Function for the user interface*/
void process_child(int input)
{

   FILE *fp;

   fp=fdopen(input,"w");
   
   if(fp==NULL)
   { 
      perror("fdopen");
      exit(0);
   }

   /*get the input from the user*/
   for(;;){

            char user_input[20]; /*assuming a max of 20 numbers is entered*/

            fgets(user_input,sizeof(input),stdin);
            if (user_input[0]!='0' && user_input[1]!='\n')
                 break;
            fputs(user_input,fp);
      
             }
 }  
   


void process_parent(int output)
{

  FILE *fp;
  int i;
 
  fp=fdopen(output,"r");

    if(fp==NULL)
    {
        perror("fdopen");
        exit(0);
    }
  
  /*read from the file*/
  for(;;){

           char buf[20];
           char *p;
           int number;
           p=fgets(buf,sizeof(buf),fp);
           /*check for end of file*/
           if(p==NULL)
               break;
           /*convert string to integer*/
           sscanf(buf, "%d", &i);
           printf("%d\n",i);
           process_thread(i);
      
         }
}

> fgets(user_input,sizeof(input),stdin);
What is input in this context?

It's more usual to write fgets(user_input,sizeof(user_input),stdin);

Thanks fixed that.
but the program still terminates whenever I enter a number with more than one digit

So what's your latest code?
And what calls process_parent() ?

Also, process_parent() calls process_thread, not process_child.
We're not exactly dealing with full information here.

thank you for your help, i found the problem is here

if (user_input[0]!='0' && user_input[1]!='\n')
                 break;

it worked when i changed it to

if (user_input[0]!=='0' && user_input[1]!=='\n')
                 break;

I'm sorry that was a typo I meant !=, the problem was when it got a number of two digits the condition would apply and the loop breaks (true & true)
if (user_input[0]!='0' && user_input[1]!='\n')
but when the number is one digit ( true & false) the loop won't break

Is the rest of it a typo as well, because I've lost all confidence in what you're posting has anything to do with what you're running.

Also, are you mixing fgets() calls with scanf() calls somewhere else in your program. This too will mess things up.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.