Error executing when using scanf

2

I can not execute any program that carries calculation operations in all the compilers that I have installed in my Computer.

#include<stdlib.h>
#include<stdio.h>
int main(){
    int num,tot;

    printf("Ingrese un Numero:");
    scanf("%d",num);
    tot=num+2;
    printf("El resultado es: %d");
    system("PAUSE");
}

This error message appears in all the compilers: "The program has stopped working", accompanied by the option "Close program".

    
asked by Ark 22.05.2017 в 21:06
source

2 answers

3

Your code has 2 faults:

  • scanf("%d",num); , the function scanf receives arguments to scan values by format, which is the famous %d that you have in quotes, scanf needs the memory address where this value will be assigned ... And in the way that you have it now, you are passing it the value of the variable num .
  • Solution:

    scanf("%d", &num); /* Con esto se arregla. */
    
  • printf("El resultado es: %d"); function printf when you find a %* (where% is% of a format specifier) 1 , the first thing you do is find the corresponding argument passed to the function, which in your case, is not available and can be indefinite compotamiento 2 .
  • In addition to this, if you put the * but do not put the variable, you will not see the value of the variable.

    Solution:

    printf("El resultado es: %d", num); /* Pasa la variable num. */
    

    Leaving the complete code:

    #include<stdlib.h>
    #include<stdio.h>
    
    int main(void) {
        int num, tot;
    
        printf("Ingrese un Numero:");
        scanf("%d", &num);
        tot = num + 2;
        printf("El resultado es: %d", tot);
        system("PAUSE");
    
    }
    

    I have tried the code that I have put before and it works perfectly (Ubuntu 14.04) and this is the result that it throws using 5 as an introduced number:

    Ingrese un Numero:5
    sh: 1: PAUSE: not found
    El resultado es: 7
    

    As seen in the second line, %d is because sh: 1: PAUSE: not found is not available in Linux, it is only valid in Windows.

    1 : Reference: What is the use of the operator% in printf of variables in language C?
    2 : While it may work on certain platforms, in others it is undefined behavior, but if PAUSE does not find an argument it just jumps.

        
    answered by 22.05.2017 в 21:19
    0

    You need to indicate the memory address, in the variable num with the & that indicates the memory address of the variable, putting &num within the function scanf();

        
    answered by 23.05.2017 в 17:27