[英]Reading intergers from a text file in c
我想將文件中的輸入輸入到我的C程序中。 輸入應包含數字和字符,此后我要區分它們。 由於fscanf在遇到非整數時返回0,因此不值得在這里使用,該怎么辦?
#include <stdio.h>
#include <ctype.h>
int main(){
int num, status;
FILE *fp = fopen("data.txt", "r");
while(EOF!=(status = fscanf(fp, "%d", &num))){
if(status == 1){
printf("%d\n", num);
} else { //if(status == 0){
(void)fgetc(fp);//replace by @chux's suggestion
詮釋 while(EOF!=(ch = fgetc(fp))&& ch!='-'&&!isdigit(ch)); if(ch =='-'){int pch = fgetc(fp); if(isdigit(pch)){ungetc(pch,fp); ungetc(ch,fp); }}其他{ungetc(ch,fp); }
}
}
fclose(fp);
return 0;
}
只需一次讀取一個文件一個字符並檢查值的范圍,因為我們知道'0'到'9'的整數值是48到57,只需檢查並使用即可。 希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.