Hi all! I have been given the task to modify the code below so that it can do subtraction, multiplaction and division, not just addition. Could someone help me with this and explain what the strncpy does? I'm so confused!!


// C Parsing Adder program
#include <stdio.h>
#include <string.h>
// the code starts here
void main()
{
// declare the variables
char user_input[100] , operand1str[100] , operand2str[100] ;
char * operator_address;
float operand1, operand2, result;
// get an addition from the user, as a string
puts ("Parsing Adder: Please Enter an Addition");
gets ( user_input);
// find the address of the operator (i.e. +) in the user's string

operator_address = strchr( user_input, '+' );
// extract the first operand (the one before the operator)
strncpy ( operand1str, user_input, operator_address - user_input );
// extract the second operand (the one after the operator)
strcpy ( operand2str, operator_address + 1 );
// convert the operands to float, perform the addition and print the result
sscanf ( operand1str , "%g", &operand1 ) ;
sscanf ( operand2str , "%g", &operand2 ) ;
result = operand1 + operand2 ;
printf ( "= %g\n", result ) ;
}

strncpy() is just like strcpy() but you can specify the maximum number of characters to be copied. But you have to be careful with that function because it will not null terminate the destination sting if the source string is longer than the number of characters you specfy in the third argument. For example, if the source string is "Hello World" and you tell strncpy() to copy only 3 bytes then strncpy() will not null terminate the destination string because "Hello World" contains more than 3 characters.

In the case of the code you posted it would be better if the writer had flooded the destination buffer with 0 before calling strncpy() just to make sure the sring is null-terminated.

This article has been dead for over six months. Start a new discussion instead.