c - "static char"与 C 中的 "char"

标签 c static char scanf

为了练习变量声明、占位符和 I/O 调用,我在我用来学习的书中做了一个示例作业。然而,我一直遇到一个特殊的问题,当我试图为输入目的声明多个字符变量时,即使编译器没有捕获任何语法错误,程序在执行时也只会返回一个字符变量.这是有问题的代码:

#include <stdio.h>

int main()

{
double penny=0.01;
double nickel=0.05;
double dime=0.1;
double quarter=0.25;

double value_of_pennies;
double value_of_nickels;
double value_of_dimes;
double value_of_quarters;
double TOTAL;
int P;
int N;
int D;
int Q;
char a,b; 

//used "static char" instead of "char", as only using the "char" type caused a formatting error where only the latter character entered in its input would appear

printf("Please enter initials> \n");
printf("First initial> \n");
scanf("%s", &a);
printf("Second initial> \n");
scanf("%s", &b);

//"%s" was used as the input placeholder for type "char"

printf("%c.%c., please enter the quantities of each type of the following coins.\n", a, b);


printf("Number of quarters> \n");
scanf("%d", &Q);
printf("Number of dimes> \n");
scanf("%d", &D);
printf("Number of nickels> \n");
scanf("%d", &N);
printf("Number of pennies> \n");
scanf("%d", &P);

printf("Okay, so you have: %d quarters, %d dimes, %d nickels, and %d pennies.\n", Q, D, N, P);

value_of_pennies=penny*P;
value_of_nickels=nickel*N;
value_of_dimes=dime*D;
value_of_quarters=quarter*Q;

TOTAL=value_of_quarters+value_of_dimes+value_of_nickels+value_of_pennies;

printf("The total value of the inserted coins is $%.2lf. Thank you.\n", TOTAL);

//total field width omitted as to not print out any leading spaces
return(0);
}

这是转录的输出(“a”、“e”和四个“1”是示例任意输入值:

Please enter initials>
First initial>
a
Second initial>
e
.e., please enter the quantities of each type of the following coins.
Number of quarters>
1
Number of dimes>
1
Number of nickels>
1
Number of pennies>
1
Okay, so you have: 1 quarters, 1 dimes, 1 nickels, and 1 pennies.
The total value of the inserted coins is $0.41. Thank you.

我输入了字符“a”和“e”作为字符变量“a”和“b”的输入值,但只有“e”出现了。另一方面,如果我在“char”变量声明中放置了“static”,则两个输入的 char 值都将显示在相关的 print 调用中。

为了将来引用,我想问一下为什么会这样,以及声明中“静态”一词的值(value)。

(顺便说一句,我知道我可以简单地将“value_of_(在此处插入硬币)”变量作为常量宏。)

最佳答案

定义如下

char a,b; 

写这样的语句

scanf("%s", &a);
scanf("%s", &b);

调用 undefined behaviour . %s 不是 char 的格式说明符。使用错误的格式说明符会导致 UB。您应该使用 %c扫描 char

详细说明,

  • %s 格式说明符需要一个相应的参数,该参数是指向 char 数组的指针。它扫描多个字符,直到遇到空格(空白字符,迂腐)或换行符或EOF。
  • %c 格式说明符需要一个相应的参数,该参数是指向 char 变量的指针。它只从输入缓冲区读取一个 char

因此,对于 %s,如果您提供 char 变量的地址,它将尝试访问超出分配的内存区域以写入扫描的 数据,将调用 UB。

您可能想在 printf() 上阅读更多内容, scanf()format specifiers在前进之前。

关于c - "static char"与 C 中的 "char",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808082/

相关文章:

c - C中的冒泡排序文件

c - 链接到我创建的 DLL

c++ - 存储类别、存储持续时间、文件范围、生命周期、链接困惑

c# - 实例类的静态成员

C++ 剪切字符指针

c++ - 一个处理 char* 和 wchar_t* 的函数

c - 不使用 sting 库交换字符串的单词并使用指针

c - 函数地址与其他变量地址几乎相同

c++ - 如何将字符数组中的前 i 个字符复制到 C++ 中的另一个字符数组中?

c - 使用 c 访问/私有(private)/等