none
Using Visual Studio to write a C-code

    Question

  • Hi,

    I am trying to write down a C-code using Visual Studio 2015.

    I first used this video as a reference:

    https://www.youtube.com/watch?v=7QDwWIW_v2Q

    My code (see attached) worked pretty well:

    // continue.cpp : use continue to just print the positive numbers on the page
    
    
    #include<stdio.h>
    #include <ctype.h>
    main()
    
    {
    	short int a;
    	short int b = 2;
    	while (1) {
    		printf("\nplease enter a signed number:\n");
    		scanf_s("%d", &a);
    		if (isalpha(a))
    		{
    			printf("it is not a number");
    			continue;
    		}
    		else
    		{
    			if (a <= 0) continue;
    		}
    	}
    	printf("the input number is positive");
    
    
    }

    However, I closed VS and opened it, and did all the video said, but now I am getting error 4996 (which says "scanf" is not known, and use scaf_s). Then I used scanf, and run my program. 

    Now when I input a negative number to my code (which should result in the code saying: "please enter a signed number"). I get the attached run-time library error.

    I really appreciate it if you could help me out with it.

    Thursday, January 7, 2016 5:56 PM

Answers

  • You're falling victim to a bunch of legacy C (not C++) stuff.

    First of all, the type of a character when not using unicode should be char.  not short.

    if you use scan_f to scan a number using %d then you have to make sure that the user entered a value in the range -1 through 255, because that's what isalpha is expecting.

    just because isalpha takes an int and tolerates implicitly casting to int from short doesn't mean its value fits in a char.

    This is bogus code that pays no regard to the types or ranges of data that are accepted by the runtime functions used.

    In C a character literal is type int, so the library defines isalpha( int ).  C is a loaded gun, use it carefully.  In this case, everything you've done is allowable, in that it compiles, but it's incorrect (almost certainly doesn't do what you want.)  When it comes to C, it's up to you to use the language correctly.

    Thursday, January 7, 2016 8:50 PM