[英]Using pointers to return char and float values from scanf back to main function C
我不太明白為什么指針將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()
用於輸出流而不是輸入流。 您所做的操作將導致未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.