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

时间:2014-07-09 03:23:43

标签: c fopen

void main()
{
    FILE *fp1;
    char ch;
    int count = 0;

    fp1 =  fopen("Text.txt","r");
    if(fp1==NULL){
        printf("Failed to open file. Bye\n");
        exit(1);
    }
    printf("Text file exists");
    fclose(fp1);

}

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

3
nameA
nameB
nameC

我想检查此输入文件的第一个字符是否为数字。如果它缺少一个数字而不是程序将停止

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

这可以解决您的问题

void main()
{
    FILE *fp1;
    char ch;
    int count = 0;
    fp1 =  fopen("Text.txt","r");

    if(fp1==NULL){
        printf("Failed to open file. Bye\n");
        exit(1);
    }
    printf("Text file exists");
    ch = fgetc(fp1);
    if (ch < '0' || ch > '9') {
        fclose(fp1);
        printf("Exit: First character is not a number\n");
        return;          // first character of the input file is not number so exit
    }

    fclose(fp1);
}

答案 2 :(得分:0)

#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. Bye\n");
        exit(1);
    }
    printf("Text file exists\n");
    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. Bye\n");
            exit(1);
        }
    } else {
        printf("No contents of the file. Bye\n");
        exit(1);
    }

    fclose(fp1);
    return 0;
}