0

I want to take words from file.And I am send to array. I did this with fscanf. But, it is taking numbers, characters(, . % & # ! ?) and other things. How can I control this statement ?

int main(void) 
{       
  char path[100];
  printf("Please, enter path of file: "); scanf("%s",&path);
  FILE *dosya;
  char kelime[1000][50];
  int i=0;

  if((dosya = fopen(path,"r")) != NULL)
  {
    while(!feof (dosya))
    {
        fscanf(dosya,"%s",&kelime[i]);
        i++;
    }
  }
  else{printf("Not Found File !");}
  fclose(dosya);
}
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
Mr.Gurbuz
  • 29
  • 5
  • 3
    Don't use `while (!feof(...))`, it will in most cases not work as expected. Instead use e.g. `while (fscanf(dosya, "%s", &kelime[i]) == 1)`. – Some programmer dude May 14 '15 at 16:18
  • 2
    As for your problem, you might find [this `scanf` (and family) reference](http://en.cppreference.com/w/c/io/fscanf) useful, especially the part about the `"%["` format. – Some programmer dude May 14 '15 at 16:18
  • BTW `fclose` should be inside the `if ... != NULL` check. Some (most?) systems will crash when closing a `NULL`. – anatolyg May 14 '15 at 17:02
  • http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell May 15 '15 at 04:09
  • 2
    `Not Found File !` is what is known as a useless error message. `if((dosya = fopen(path,"r")) == NULL ) { perror(path);}` – William Pursell May 15 '15 at 04:11
  • Why are you giving `scanf` the address of `path`? `scanf("%s",&path);`? `path` is already a pointer, so `path` is all you need. (may help some of those strange characters disappear as well...) – David C. Rankin May 15 '15 at 04:48

2 Answers2

2

Use "%[]" to distinguish between letters and non-letters.

#define NWORDS (1000)
char kelime[NWORDS][50];

size_t i;
for (i=0; i<NWORDS; i++) {
  // Toss ("*" indicates do not save) characters that are not ("^" indicates `not`) letters.
  // Ignore return value
  fscanf(dosya, "%*[^A-Za-z]");

  // Read letters
  // Expect only a return value of 1:Success or EOF:no more file to read
  // Be sure to limit number of characters read: 49
  if (fscanf(dosya, "%49[A-Za-z]", kelime[i]) != 1) break;
}

// do something with the `i` words
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1

You can use fgetc()

char str[1000];
while((ch=fgetc(fname))!=EOF)
{
        // Write your code here;
        if((ch>='0' && ch<='9') || (ch<'a' && ch>'z') || (ch<'A' && ch>'Z'))
              continue;
        str[i++]=ch;
}
str[i]='\0';

When you use fscanf() the statement can't be parsed. So you have to

  1. check it char by char

  2. If not special characters or number then add to string

Subinoy
  • 478
  • 7
  • 22