[英]variable is losing its value in c program
這是用“ c”編寫的,並使用gcc進行了編譯。 我不確定您還需要知道什么。
我可以放在一起的最小的完整示例如下所示。 變量“ numatoms”到達第23行時(在scanf()之后)將失去其值。
我很沮喪 也許與scanf()覆蓋了numatoms的空間有關?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
/*
*
*/
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];
do {
printf("NO. OF ATOMS?");
fflush(stdout);
scanf("%d", &numatoms);
printf("\r\n");
for(;;){
printf("value of numatoms is %u\r\n", numatoms);
printf("RAY?");
fflush(stdout);
scanf("%u", &r);
printf("value of numatoms is %u\r\n", numatoms);
if(r < 1)
break;
else {
printf("value of numatoms is %u\r\n", numatoms);
}
}
printf("CARE TO TRY AGAIN?");
fflush(stdout);
scanf("%s", a);
printf("\r\n");
} while (a[0] == 'y' || a[0] == 'Y');
return (EXIT_SUCCESS);
}
uint8_t
為8位長, %u
讀取無符號的int(可能為32位長)。
您要么需要使numatoms
“更大”(即unsigned int
),要么要讀取正確的大小(請參閱scanf無法掃描到inttypes(uint8_t) )。
您應該將宏用於標頭<inttypes.h>
定義的整數類型的格式說明符。
來自C標准(格式說明符的7.8.1宏)
1以下每個類似於對象的宏都擴展為包含轉換說明符的字符串文字,該字符串說明符可能由長度修飾符修改,適用於在轉換相應的整數類型時在格式化的輸入/輸出函數的format參數中使用。 這些宏名稱的通用格式為PRI(fprintf和fwprintf系列的字符字符串文字)或SCN(fscanf和fwscanf系列的字符字符串文字)217),后跟轉換說明符,后跟對應於類似名稱的名稱。在7.20.1中輸入名稱。 在這些名稱中,N代表7.20.1中描述的類型的寬度。
用於帶有轉換說明符u
無符號整數類型的宏的一般形式如下
SCNuN
這是一個示范節目
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main(void)
{
uint8_t x;
scanf( "%" SCNu8, &x );
printf( "x = %u\n", x );
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.