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

Changing sentence inside a printf

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

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

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*

>Solution :

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);
}
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