Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the code in c not end and forces me to press crl+z to end the execution?

I´ve made a simple code to print in reverse the numbers written between letters.
For example: if I write on the terminal:
1 2 3 hello 4 5 6 end
or enter that in the function through a txt its returning the expected values:
3 2 1\n
6 5 4\n
but it doesn´t end, Im forced to press crl+z to be able to use the trminal again.

#include <stdio.h>
#include <stdlib.h>

#define MAX_NUM 64

int main() {
    int num[MAX_NUM];
    int size = 0, i;
    char word[20];
    while (scanf("%d", &num[size]) != 0) {
        size++;
        while(scanf("%d", &num[size]) != 0){
            size++;
        }
        if (scanf("%s",word) != 0 || size == MAX_NUM) {
            for (i = size - 1; i >= 0; i--) {
                if(i == 0)
                    printf("%d", num[i]);
                else
                    printf("%d ", num[i]);
            }
            printf("\n");
            size = 0;
        }
    }
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why does the code in c not end and forces me to press crl+z to end the execution?

Because scanf cannot read your mind. For instance, when you call scanf("%d", &num[size]) and there is not presently any more data available to read, scanf doesn’t know that you don’t intend ever to present any more. Before it returns, it needs to see an end-of-input or error signal or a character that it cannot match to the format. In Windows, Ctrl-Z signals end-of-input on the standard input of a program running in the terminal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading