如何判断输入文件的第一个字符是否为数字?C编程


void main()
{
    FILE *fp1;
    char ch;
    int count = 0;
    fp1 =  fopen("Text.txt","r");
    if(fp1==NULL){
        printf("Failed to open file. Byen");
        exit(1);
    }
    printf("Text file exists");
    fclose(fp1);
}

输入文件示例(Text.txt)-

3
nameA
nameB
nameC

我想检查这个输入文件的第一个字符是否是一个数字。如果缺少一个数字,程序将停止

包含ctype.h,然后有一些函数进行类型检查。或者检查该字符的值是否在适当的ASCII范围内。

这会解决你的问题

void main()
{
    FILE *fp1;
    char ch;
    int count = 0;
    fp1 =  fopen("Text.txt","r");
    if(fp1==NULL){
        printf("Failed to open file. Byen");
        exit(1);
    }
    printf("Text file exists");
    ch = fgetc(fp1);
    if (ch < '0' || ch > '9') {
        fclose(fp1);
        printf("Exit: First character is not a numbern");
        return;          // first character of the input file is not number so exit
    }
    fclose(fp1);
}
#include <stdio.h>
#include <stdlib.h>
int main(){
    FILE *fp1;
    char ch, line[128];
    int count = 0, num;
    fp1 =  fopen("Text.txt","r");
    if(fp1==NULL){
        printf("Failed to open file. Byen");
        exit(1);
    }
    printf("Text file existsn");
    if(fgets(line, sizeof(line), fp1)){
        if(1==sscanf(line, "%d", &num)){
            while(num-- && fgets(line, sizeof(line), fp1)){
                printf("%s", line);
            }
        } else {
            printf("The beginning of the file is not numeric. Byen");
            exit(1);
        }
    } else {
        printf("No contents of the file. Byen");
        exit(1);
    }
    fclose(fp1);
    return 0;
}

最新更新