Как написать программу, которая считает количество чисел в файле - PullRequest
0 голосов
/ 27 декабря 2018

Мне нужно написать программу на C, которая подсчитывает, сколько чисел содержится в файле. Предположим, данный файл указан ниже

ФАЙЛ:

 Lorem ipsum dolor sit amet 103 consectetur adipiscing elit. 103.55 
 Phasellus nec neque posuere 103.55e-67 nulla sagittis efficitur.

ВЫХОД:

There are 3 numbers in file.

, которые составляют 103, 103,55 и 103,55e-67.

Я понимаю, что в C я могу читать символ за символом, используя fgetc(), повторяя до EOF.Как можно получить последовательности цифр, как в приведенном выше выводе.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
  FILE * file;
  char path[100];

  char ch;
  int numbers[200];
  int number_count;



  printf("Enter source file path: ");
  scanf("%s", path);


  file = fopen(path, "r");



  if (file == NULL)
  {
    printf("\nUnable to open file.\n");
    printf("Please check if file exists and you have read privilege.\n");

    exit(EXIT_FAILURE);
  }



  /* Finding and counting numbers */

  while ((ch = fgetc(file)) != EOF){

    // What logic do i write here??

  } 


  printf("The file has %d numbers.\n", number_count);

  return 0;
}

Ответы [ 3 ]

0 голосов
/ 24 января 2019

Что мне было нужно, так это реализация.

# include <stdio.h>
# include <string.h>
# include <ctype.h>
# include <stdlib.h>

void count_numbers(){

    FILE * file;  
    char c, str[1000], path[100]; 

    int number_count = 0, i=0, check=0, state = 12;

    printf("Enter source file path: ");
    scanf("%s", path);

    /* Open source file in 'r' mode */
    file = stdin;
    file = fopen(path, "r");

    /* Check if file opened successfully */
    if (file == NULL)
    {
        printf("\nUnable to open file.\n");
        printf("Please check if file exists and you have read privilege.\n");

        exit(EXIT_FAILURE);
    }

    /* Read file content, store characters to a pointer str, and counting numbers */
    fread(str, 1000, 1000 ,file);
    int leng = strlen(str);

    while(check==0){
        if(i==(leng+1))
            check = 1;

        switch (state){
            case 12: c = str[i];
                if(isdigit(c)) { state = 13; i++; }
                else { state = 12; i++; }
                break;
            case 13: c = str[i];
                if(isdigit(c)) { state = 13; i++; }
                else if(c == '.') { state = 14; i++; }
                else if (c == 'E' || c == 'e') { state = 16; i++; }
                else {state = 20; number_count++; i++; }
                break;
            case 14: c = str[i];
                if(isdigit(c)) { state = 15; i++; }
                else{ state = 0; number_count++; i++; }
                break;
            case 15: c = str[i];
                if(isdigit(c)) { state = 15; i++; }
                else if (c == 'E' || c == 'e') { state = 16; i++; }
                else {state = 21; number_count++; i++; }
                break;
            case 16: c = str[i];
                if (c == '+' || c == '-') { state = 17; i++; }
                else if(isdigit(c)) { state = 18; i++; }
                break;            
            case 17: c = str[i];
                if(isdigit(c)) { state = 18; i++; }
                break;
            case 18: c = str[i];
                if(isdigit(c)) { state = 18; i++; }
                else { state = 19; number_count++; i++; }
                break;
            case 19: state = 12;
                break;        
            case 20: state = 12;
                break;       
            case 21: state = 12;
                break; 
        }
    }

    /* Close source file */
    fclose(file);

    /* Print the count value of numbers obtained from the source file */
    printf("\n Number of numbers is %d \n", number_count);
}

int main(){
    count_numbers();
    return 0;
}
0 голосов
/ 24 января 2019

Просто проверьте, находится ли символ, который вы читаете из файла, в диапазоне значений ascii чисел, т.е.0 = 48 и 9 = 57 в ascii.Если это так, просто увеличьте значение числа num

#include <stdlib.h>
#include <ctype.h>

int main()
{
  FILE * file;
  char path[100];

  char ch;
  int numbers[200];
  int number_count;



  printf("Enter source file path: ");
  scanf("%s", path);


  file = fopen(path, "r");



  if (file == NULL)
  {
    printf("\nUnable to open file.\n");
    printf("Please check if file exists and you have read privilege.\n");

    exit(EXIT_FAILURE);
  }



  /* Finding and counting numbers */
  number_count = 0;
  while ((ch = fgetc(file)) != EOF){

    if(ch >= 48 && ch <=  57)
    {
       number_count++;
     }

  }     



  printf("The file has %d numbers.\n", number_count);

  return 0;
}


0 голосов
/ 27 декабря 2018

Попробуйте это:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    FILE * file = stdin;
    int number_count = 0;

    for (;;) {
        // scan a long double number
        long double tmp;
        if (fscanf(file, "%lf", &tmp) == 1) {
            number_count++;
            // find two numbers one after another
            continue;
        }
        // discard data until whitespace
        // this will also break on end of file
        if (fscanf(file, "%*s") == EOF) {
            break;
        }
    }

    printf("The file has %d numbers.\n", number_count);
    return 0;
}
  • Я использую fscanf с "%lf" модификатором scanf для сканирования одного номера
  • Если номер успешно отсканирован, счетчикувеличивается и цикл возвращается
  • , если число не сканируется, мы пропускаем одну строку (* в "%*s" отбрасывает строку)
  • если scanf возвращает EOF, это означает, что конец файластолкнулся, и мы должны начать отсчет
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...