0

Vala newbie here. Learning Vala as programming language and stuck with following program

int main() {
    string first_name;
    string last_name;
    uint age;

    stdout.printf("Enter your first name: ");
    first_name = stdin.read_line();

    stdout.printf("Enter your last name: ");
    last_name = stdin.read_line();

    stdout.printf("Enter your age: ");
    age = stdin.scanf("%u", out age);

    stdout.printf("Hi! %s %s. You are %u years old.\n", first_name, last_name, age);

    return 0;
}

This program is working fine except the value of %u or age. Whatever value that I entered, it always printing 1.

Thank You in Advance.

1

You're assigning the return value to age. The return value for scanf is documented as:

On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

Since you're attempting to read 1 value, if the input is read successfully the return value will be 1.

Try something like

if (stdin.scanf("%u", out age) < 1) GLib.error("Unable to parse age");

  • Got your point. But, is there way I can get the entered value of age and display it. For example, if I entered 24, then it should display 24 as age? – Kiran Jan 4 '18 at 6:16
  • With the line I posted age should contain 24. Notice that you're still passing age as an out param to scanf, you're just not clobbering it with the return value afterwards. – nemequ Jan 4 '18 at 12:27
  • aha! age = should not be there. Got it. Thanks. – Kiran Jan 4 '18 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.