简体   繁体   中英

Why does my C program close early?

I am having a very confusing problem right now. I wrote a test program for myself, but sometimes after I input Crtl+C, which is what I assume to be the EOF, the program closes early without running through some more commands below the While Loop I wanted it to cancel from.

#include <stdio.h> 
#include <string.h>

int main()
{
char message[140];
    char* p = message;
     int count;
int i = 0;
    int charGT;
    while((charGT=getchar()) != EOF) 
    {
        message[i] = charGT;
        i++;
        printf("%d" , i);
    }
    printf("next");
    count = strlen(p);
    printf("%d", count);
    printf("after");
    return (0);
}

Inputting "asd\\n^C" will cause my program to end early. "next" or "after" will not be printed My theory is that somehow, the \\n is causing the program to step out of the loop for a moment, and then Crtl+C is exiting the program, but I don't know how that would work.

Ctrl + C is the break command and will send an interrupt signal to your application. The default handler will cause this to exit the process.

Ctrl + D is the EOF command you are looking for.

For running on windows, to enter EOF press Ctrl+Z and then press ENTER. In UNIX systems it is Ctrl+D, in Windows Ctrl+Z.

When a program is running if you press Ctrl-c a signal is sent to abort the program and the program is aborted. However, if you want to use Ctrl-c as an input but not abort the program write one signal handler which catches the signal when you press Ctrl-c and perform the action you wanted to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM