英文:
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 = 1,integer = 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 <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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论