将计算结果存入结构体字段的char类型中

huangapple go评论58阅读模式
英文:

Getting calculation into struct field type of char

问题

以下是翻译好的部分:

我声明了以下的结构体

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

我有一个函数:

    int add_number(int num1, STRUCT *pointer) {
       int integer;
       int sum;
       printf("\n请输入要相加的整数: ");
       scanf("%d", &integer);
       sum = num1 + integer;
       printf("%d+%d=%d\n", num1, integer, sum);
       scanf("%s", pointer->calculation);   // 这里我想要将 %d+%d=%d 存储到 pointer->calculation 中
       num1 = sum;
       return num1;
    }

我想要将这个:

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

存储到这里:

    pointer->calculation

(例如,如果 num1 = 1integer = 2,我想要将 "3 = 1 + 2" 存储到 pointer->calculation )

如何实现这个?我不太明白。
英文:

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:

"%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.

答案1

得分: 0

你可以使用例如 snprintf 来将格式化的字符串打印到缓冲区中(类似于 printf,但不是直接输出到标准输出,而是输出到缓冲区)。

例如:

#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);
}

输出:

1+2=3

传递给 snprintf 的大小是29,而不是30,因为我们需要为字符串的零终止保留一个元素。

注意: 你写道你希望缓冲区包含 3 = 1 + 2,但这与你的字符串格式 "%d+%d=%d\n" 不符,所以我假设你希望得到 1+2=3

英文:

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 &lt;stdio.h&gt;

int main()
{
	int num1 = 1;
	int integer = 2;
	int sum = num1 + integer;
	char buf[30];
	snprintf(buf, 29, &quot;%d+%d=%d\n&quot;, 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 &quot;%d+%d=%d\n&quot;, so I assume you meant you'd like 1+2=3.

huangapple
  • 本文由 发表于 2023年2月6日 17:18:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定