Zyphicx
Zyphicx

Reputation: 309

Program stops running after while loop

So, it has been some time since I last programmed in C, and now I am trying to get back into C again, but I am having trouble with my program. The program is very simple, I use getchar to store chars in a char array, but for some reason the program stops running after my while loop.

#include <stdio.h>
#define MAXLINE 1000

int main(){
    char c;
    char input[MAXLINE];
    int i = 0;

    while((c = getchar()) != EOF){
         input[i] = c;
         ++i;
    }
    printf("Still running");
}

So, my program doesn't print "Still running".

Upvotes: 1

Views: 930

Answers (2)

Lundin
Lundin

Reputation: 214860

Your program only works by luck, because getchar returns an int not a char. The reason for this is that getchar may return EOF, which is not necessarily representable as a char.

To fix this bug, you need to replace char c with int c.

Upvotes: 1

meAbab
meAbab

Reputation: 102

Send EOF (Ctrl+D for *nix Ctrl+Z for Win), it will show the Still running.

root@Linux-VirtualBox:~/program/progEdit# ./stktest.o 
sdf 
fdf 
sdf 
Still runningroot@Linux-VirtualBox:~/program/progEdit#

Upvotes: 2

Related Questions