我不太明白为什么指针将值从 scanf 从 info 函数传递到 main 函数,但我刚刚在 info 函数中定义的函数没有传递回 main 函数。我是否需要 do while 循环来实现确保用户为 ab 和 c 输入值的目标?
#include <stdio.h>
void info (char *a, char *b, char *c);
void main(void)
{
char lett1 = 'a', lett2 = 'b', lett3 = 'c';
info (&lett1, &lett2, &lett3);
printf("\n The characters chosen are: %c, %c and %c", lett1, lett2, lett3);
}
void info (char *a, char *b, char *c)
{
a = 'E';
printf("\n Type any 2 characters then press enter: ");
fflush(stdin);
scanf(" %c", b);
do{
scanf(" %c", c);
}while (c == NULL);
}
第二段代码是我也使用指针和 scanf 但我无法让程序工作的地方。当我使用我注释掉的部分时,(type = 'A' 或 type = 'B')它可以工作,但不适用于 scanf。此外,输入函数中定义的值永远不会移动到主函数。
#include <stdio.h>
void input (char *type, float *BU_Dist, float *SC_Dist, float *DC_Dist);
void main (void)
{
char type_M = 'Z';
float BU_Dist_M, SC_Dist_M, DC_Dist_M;
input (&type_M, &BU_Dist_M, &SC_Dist_M, &DC_Dist_M);
printf("Value back in the main is %c", type_M);
}
void input (char *type, float *BU_Dist, float *SC_Dist, float *DC_Dist)
{
printf("Which car type (A/B):");
fflush(stdin);
scanf("%c", type);
//type = 'A'
//type = 'C';
printf ("%c \n\n", type);
if(type == 'A'|| type == 'B'||type == 'a'||type == 'b') {
printf("\nGreat! &c selected! \n", type);
}else{
type = 'A';
printf("\nInvalid value selected, type has been defaulted to %c \n", type);
}
}
任何帮助理解指针和 scanf 在主函数以外的函数中如何协同工作都会非常有用。谢谢
在注释部分中,您将 char 值分配给char*
导致未定义行为的结果。
同样在这段代码中,你也做了type='A'
基本上没有涵盖的代码,因为我认为代码没有转到其他部分。
如果你想分配,你会这样做*type='A'
。
为了进行比较,您需要取消引用char*
以获取值。
if(*type == 'A'|| *type == 'B'||*type == 'a'||*type == 'b') {
也fflush()
意味着用于输出流而不是输入流。你所做的会调用未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句