0

If my file finished with the word whose frequency i have to calculate then it will give one more than actual value other wise it is ok.

int n=0;
char search[40];
  cin>>search;
  char* a=search;
  while(fin){
      char c[40];
      fin>>c;
      char* b=c;
      if(*a==*b)
      n++;

  }
cout<<n;

How can i overcome the problem even if i use strcmp then still same thing happens.

  • 1
    `if(*a==*b)` just compares the first character of both strings. Is this really what you want? Or did you mean [`strcmp()`](https://en.cppreference.com/w/cpp/string/byte/strcmp)? (just noticed you said you tried using `strcmp`. How did that call look?) – scohe001 Feb 24 '20 at 21:42
  • You tagged the question with C++ but you use C-strings. Is there a test for this? You should use `std::string` – Thomas Sablik Feb 24 '20 at 21:49
  • [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Thomas Sablik Feb 24 '20 at 21:50

1 Answers1

3

Your problem is with how you have your loop setup.

while(fin) will check if fin is valid--which it will be, right up until a call of fin >> c fails (which is likely at the end of the file). So even if you've read everything there is to read, you'll still enter the loop one more time, run fin >> c, which fails and does nothing to c, and then run the same comparison you did an iteration before.

Instead, I'd refactor this as:

int n = 0;
char search[40], tmp[40];
cin >> search;
char* a=search;
while(fin >> tmp){
    char* b = tmp;
    if(strcmp(a, b) == 0) { n++; }
}
cout<<n;

See it work (with everything in stdin) here: https://ideone.com/sWZtHp

scohe001
  • 13,879
  • 2
  • 28
  • 47
  • yes but the catch is I can't use header files other than iostream and fstream – Sourav kumar Feb 26 '20 at 19:42
  • @Souravkumar `strcmp` wouldn't be too hard to remake yourself: https://stackoverflow.com/a/22974014/2602718 – scohe001 Feb 26 '20 at 20:05
  • yes it really helped....but can you please help me understand this code... – Sourav kumar Feb 26 '20 at 20:56
  • int my_strcmp(const char *a, const char *b) { while (*a && *a == *b) { ++a; ++b; } return (int)(unsigned char)(*a) - (int)(unsigned char)(*b); } – Sourav kumar Feb 26 '20 at 20:56
  • why are we giving a and the a==b in while loop, instead of just a==b – Sourav kumar Feb 26 '20 at 20:57
  • @Sourav `*a` evaluates to true as long as it's not pointing to the null character (`\0`) which signifies the end of a string. However, explaining all of that code to you would be enough for another question and answer--far too much for just a comment. There are plenty more `strcmp` implementations out there though if you google around. If you still can't find good explanations or a simpler implementation you can understand, feel free to ask another question :) – scohe001 Feb 26 '20 at 20:58