簡體   English   中英

C程序讀取文件並只打印數字

[英]C program to read a file and print just the numbers

我有一個包含字符串和數字的文件。 例如。 我的文件Store-1.txt包含“coffee 2mug -4”。 我需要ac程序只通過讀取文件並將數字保存到數組中來存儲數字(即2和-4)。

我無法弄清楚到底是怎么做到的。 請給我任何建議。

代碼是

#include <stdio.h>


int main(void)
 {
 char c,ch;
 int flag=0;
  FILE *fptr=fopen("Store-1.txt","r");
  if(fptr)
 {
 while((c=fgetc(fptr))!=EOF)
 {
 if(c=='-' || c== '+')
     {
      ch=c;
      flag=1;
     }
 if(c>='0' && c<='9')
  {
    if(flag == 1)
     { 
       printf("%c",ch); flag =0;
      }
   printf("%c",c);
  }
   }
   }
  else
printf("Error : file not found");

  system("pause");
 }

如果使用fgetc()printf()讀取文件

c>='0' && c<='9'

這是完整的工作代碼:

#include <stdio.h>
int main()
{
char c,ch;
int flag=0;
FILE *fp=fopen("file.txt","r");
if(fp)
{
    while((c=fgetc(fp))!=EOF)
    {
     if(c=='-' || c== '+')
         {
          ch=c;
          flag=1;
          continue;
         }
     if(c>='0' && c<='9')
      {
        if(flag == 1)
         {
           printf("%c",ch); flag =0;
          }
       printf("%c",c);
      }
     else
        flag=0;
    }
}
else
    printf("Error : file not found");

fclose(fp);}
#include <ctype.h>
#include <stdio.h>

int main(void)
{
   int ch, n, sign;

   sign = 1;
   ch = getchar();
   while (ch != EOF) {
      if (ch == '-') {
         sign = -1;
         ch = getchar();
      } else if (isdigit(ch)) {
         n = 0;
         do {
            n = n * 10 + ch - '0';
            ch = getchar();
         } while (isdigit(ch));
         n *= sign;
         /*store n*/
      } else {
         sign = 1;
         ch = getchar();
      }
   }
   return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM