i'm new to C and i have these line of codes
int Input(char c)
{
printf("input number %c: ",c);
scanf("%d", &a);
return a;
}
void main()
{
int n;
n = Input('A'); // n = a ;
printf("The number you just input is %d", n);
return;
}
Output:
Input number A:
5
The number you just input is
5
But i'm wondering if i can replace the "input number %c: "
which another string like "input a number above 0"
using the called function in main()
int Input(char c)
{
printf("%s: ",c);
scanf("%d", &a);
return a;
}
void main()
{
int n;
n = Input("input a number above 0: ");
printf("The number you just input is %d", n);
return;
}
Expected Output:
input a number above 0: *input a number*
CodePudding user response:
Firstly, a
is undefined in your Input
function.
As for passing a string instead of a single character:
%c
expects a char
.
%s
expects a char *
- a pointer to a null-terminated string.
Remember to check that the return value of scanf
matches the number of conversions you were expecting, and handle the event otherwise (e.g., exit
).
int Input(const char *msg) {
int val;
printf("input number %s", msg);
if (1 != scanf("%d", &val)) {
fprintf(stderr, "Could not read integer value.\n");
exit(EXIT_FAILURE);
}
return val;
}
Usage:
int n = Input("a string");
If you want to retain string interpolation, use a variadic function.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
int get_int(const char *msg, ...) {
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
int val;
if (1 != scanf("%d", &val)) {
fprintf(stderr, "Could not read integer value.\n");
exit(EXIT_FAILURE);
}
return val;
}
int main(void) {
int n = get_int("Enter an integer (%c): ", 'A');
printf("Got: %d\n", n);
}