Validating Input with scanf_s in C++

To sum user-input numbers until a non-numeric character terminates the program, check the return value of scanf_s. It returns the count of successfully read items, so a return value of 1 indicates valid input.

#include <iostream>
#include <cstdio>

int main() {
    int value = 0;
    long total = 0L;
    int result;

    do {
        std::cout << "Enter a valid number: ";
        total += value;
        result = scanf_s("%d", &value);
    } while (result == 1);

    printf("Sum: %ld\n", total);
    system("pause");
    return 0;
}

For enhacned functionality, modify the program to accept both integers and floating-point numbers on a single line with arbitrary sepraators, outputting the sum with two decimal places. Convert all inputs to floating-point for consistency and handle multiple inputs per line by checking for newline characters.

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    float input_val = 0.0f;
    double accumulator = 0.0;
    int read_status;

    do {
        cout << "Enter valid numbers: ";
        do {
            accumulator += input_val;
            read_status = scanf_s("%f", &input_val);
        } while (getchar() != '\n' && read_status == 1);
    } while (read_status == 1);

    printf("Result: %.2lf\n", accumulator);
    system("pause");
    return 0;
}

The inner loop continues while characters other than newline are read and scanf_s succeeds. Short-circuit evaluation ensures the loop exits appropriately on newline input.

Tags: C++ input validation scanf_s Error Handling programming

Posted on Sun, 10 May 2026 21:23:57 +0000 by john010117