Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting calculation into struct field type of char

I have declared following struct

typedef struct STRUCT{
    char calculation[30];
}STRUCT;

I have a function:

int add_number(int num1, STRUCT *pointer) {
   int integer;
   int sum;
   printf("\nGive an integer to be added: ");
   scanf("%d", &integer);
   sum = num1 + integer;
   printf("%d+%d=%d\n", num1, integer, sum);
   scanf("%s", pointer->calculation);   // here I would want to get the %d+%d=%d stored into pointer->calculation 
   num1 = sum;
   return num1;
}

I would want to store this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"%d+%d=%d\n", num1, integer, sum

into this:

pointer->calculation

(So for example, if num1 = 1 and integer = 2 I would want to have 3 = 1 + 2 stored into pointer->calculation)

How could it be done? I don’t get it.

>Solution :

You can use e.g. snprintf to print a formatted string into a buffer (similar to what printf does but instead of directly to stdout).

For example:

#include <stdio.h>

int main()
{
    int num1 = 1;
    int integer = 2;
    int sum = num1 + integer;
    char buf[30];
    snprintf(buf, 29, "%d+%d=%d\n", num1, integer, sum);
    printf(buf);
}

Output:

1+2=3

The size passed to snprintf is 29 instead of 30, because we need to keep one element for the zero termination of the string.

Note: you wrote that you would like the buffer to contain 3 = 1 + 2 which does not match your string format "%d+%d=%d\n", so I assume you meant you’d like 1+2=3.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading