gpt4 book ai didi

c - 打印部分字符数组......有一个扭曲

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:07 26 4
gpt4 key购买 nike

所以我知道有很多关于在 C 中仅打印 char 数组段的问题,我已经阅读了它们,虽然我的问题在本质上是相似的,但我的问题有点不同。给出下面的代码,如何只打印出 fmt 数组的前四个字符?我不允许更改 fmt,因此我必须使用 VAL 来指定我只想打印值、换行符和一个空格。

#define VAL 4
int main() {
char fmt[10] = "%d\n ";
int value = 1;
printf(fmt, value);
}

编辑:

这只是我的代码的一小部分,因为我觉得这就是所有必要的。如果需要更多,我将提供我的其余代码。

编辑2:

限制:没有新变量 & 必须使用 VAL 来指定要打印的 fmt 数组的数量。

EDIT3(完整问题):

填补程序缺失的部分,不添加任何变量声明。要求用户选择他/她想要如何打印输入的整数值。 (如果您不了解 printf 的整数格式说明符,请查找它们。)使用指示的格式说明符字母打印先前输入的整数,然后返回,然后重新提示输入另一个格式字母(尽管不是新整数)。低于复杂性限制是挑战的主要部分。灵活选择哪种类型的循环,以及如何读取格式说明符。另请注意,如果格式字符串中的 %c 之前有空格,则 scanf 在读取字符时会跳过空格。而且,该 VAL 定义有一个重要用途,涉及消除输出中的虚假空白。最后,甚至不要考虑使用大开关或 if-else block 来执行此操作。

#include <stdio.h>
#define VAL 4 // You might want this

int main() {
char fmt[10] = "%d\n "; // Quickly initializes fmt array
int value;

printf("Enter an integer: ");
scanf("%d", &value);
//from here below is my code, above code is pre-provided
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);

while (fmt[1] != 'q') {
printf("%4s", fmt, value);
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);
}
}

最佳答案

how do I only print out the first four characters of my fmt array

怎么样:

printf("%4s", fmt);

It doesn't work because I need the variable value to tell the %d in fmt what to print out

选项:

  • 使用 4 的长度打印到单独的字符串 (snprintf)
  • 处理您的号码,直到它包含适当数量的数字,然后打印

关于c - 打印部分字符数组......有一个扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com