User input [arrays]

Is there a way I can store a double digit integer in a single array slot? Also, I know my code is completely wrong I just need help understanding a method to perform the task.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#define _CRT_SECURE_NO_WARNINGS

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

int main()
{
	char input[4]; 

	do {
		printf("Enter a value greater than 9: ");
		scanf("%s", input);
	} while (isalpha(input[0])); 

	int numValue = input[0] - '0'; 
	printf("%d\n", numValue); 

	system("PAUSE"); 
	return 0; 
}


Also, I know input[0] will just check and output the first digit of the users input. I tried numValue = input - '0';, and I believe it outputted the address of input - 48. Moreover, I tried while (isalpha(input));, and I got a Run-Time error.
Prefer to use iostreams rather than C I/O (e.g., scanf()). It's just too easy to get scanf() wrong.

That said, if you must use scanf, then read the number directly with the %d format specifier:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define _CRT_SECURE_NO_WARNINGS

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

int
main()
{
    int input;

    printf("Enter a value greater than 9: ");
    scanf("%d", &input);
    printf("%d\n", input);
    return 0;
}
Last edited on
Thanks for you help, but if I declare input as an int I cannot determine if the user entered a letter instead of a number.
Using dhayden's suggestion, check the result of scanf() to see if the call succeeded.
Last edited on
Another possibility: get the input as a string and use atoi() to convert to an integer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main()
{
    char input[80]; 
    int numValue = 0;
    
    do {
        printf("Enter a value greater than 9: ");
        scanf("%s", input);
        numValue = atoi(input);
    } while (numValue < 10); 


    printf("%d\n", numValue); 

    system("PAUSE"); 
    return 0; 
}

Topic archived. No new replies allowed.