1

So i have this problem in c++.

I open a file and read it char by char and print it on screen.

It works fine until I add this to the program.

gr=0; 

The complete program:

int main() { int gr; char *ch; gr=0;//this causes the problem FILE *fp; fp=fopen("as.txt","r"); do { *ch=fgetc(fp); cout<<*ch<<endl; } while (*ch!=EOF); } 
2
  • How does it "stop working"? Do you have debugger? That extra assignment shouldn't cause any problems. Commented Mar 14, 2015 at 21:04
  • It just says pojname.exe has stopped working Commented Mar 14, 2015 at 21:08

3 Answers 3

2
char *ch; *ch=fgetc(fp); 

You created a pointer, but you never actually made it point to anything.

That it appeared to work without the gr=0 assignment is pure chance, likely a result of various factors contributing to values in memory. When you dereference invalid pointers, sometimes you get a segmentation fault and othertimes you just silently overwrite some memory that's not yours, causing further bugs down the line.

I have no idea what you need a pointer for here, anyway. Surely simply declare a char ch and use that.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes,I don't know why I used pointers I guess I got confused.That solved the problem.Thank you.
0

Your code seg faults on me. You might try something like the code listed below.

#include <cstdio> #include <iostream> int main() { FILE *fp; char c; fp=fopen("str.cpp","r"); if(fp != NULL) { do { c=fgetc(fp); std::cout << c << std::endl; } while (c!=EOF); } } 

1 Comment

Turns out the problem was using pointer on character ch.Thank you for the answer.
0

The problem is in the char pointer.You never actually allocate memory for it it's just some random pointer thus giving you undefined behavior.This is why it worked without the gr on your machine but it's just random and it won't work in most cases.
What you want to do is allocate memory for it like that :

int main() { int gr; char *ch=new char; gr=0;//this has nothing to do with the problem FILE *fp; fp=fopen("as.txt","r"); do { *ch=fgetc(fp); cout<<*ch<<endl; } while (*ch!=EOF); delete ch; //For each new there must be a delete return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.