c - Visual Studio 2015 shows Debug Assertion Failed -


i have made simple file reading program runs in dev c gcc compiler, shows error debug assertion failed. searched , has asked same question 12 days ago, answer shows error on statement

if (file = fopen (name, "w+") == null) {   ... }     

and says separate 2 statements as

file = fopen(name, "w+");  if (fp == null) { ...}     

my code

#include<stdio.h> #include<conio.h> #include<stdlib.h> int main() {      int nos = 0, noc = 0, nol = 0;     char ch;     file *fp;     fp = fopen("sarju.txt", "r");     while (1)     {         ch = fgetc(fp);         if (ch == null)         {             printf("the file didn't opened\n");             break;         }         if (ch == eof)             break;         noc++;         if (ch == ' ')             nos++;         if (ch == '\n')             nol++;     }     if (ch != null)         fclose(fp);     printf("number of space : %d\nnumber of characters : %d\nnumber of lines : %d\n", nos, noc, nol);     _getch();     return 0; }    ` 

my error

debug assertion failed! program: ...o 2015\projects\let c solutions\debug\let c solutions.exe file: minkernel\crts\src\appcrt\stdio\fgetc.cpp line: 43 expression: stream.valid() information on how program can cause assertion failure, see visual c++ documentation on asserts. (press retry debug application)

your code has several problems. corrected code be:

#include <stdio.h> #include <conio.h> #include <stdlib.h>  int main() {     int nos = 0, noc = 0, nol = 0;     int ch; /* `int`, not `char` */     file *fp;     fp = fopen("sarju.txt", "r");     while (1)     {         /*ch = fgetc(fp); after below `if`, not here */         if (fp == null) /* `fp`, not `ch` */         {             printf("the file didn't opened\n");             break;         }         ch = fgetc(fp);         if (ch == eof)             break;         noc++;         if (ch == ' ')             nos++;         if (ch == '\n')             nol++;     }     if (fp != null) /* `fp`, not `ch` */         fclose(fp);     printf("number of space : %d\nnumber of characters : %d\nnumber of lines : %d\n", nos, noc, nol);     _getch();     return 0; } 
  1. i used int fgetc returns int, not char.
  2. you should check if fp not null, not ch.
  3. ch = fgetc(fp); @ wrong place.

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -