简体   繁体   中英

How to set value to 0 if input isn´t type in? c++

hi i am sorry if this is a silly question but i am new to programming. I can´t find how to give a value 0 to a variable unless the input says different. Looks something like this

int main() {
    // weekly accountability
    std::cout << " ...";
    std::cout << " Please write down the numbers\n";
    double a2;
    double b2;
    double c3;
    std::cin >> a2 >> b2 >> c3;
    "!\n";
    double x = 0.66;
    double sum2 =a2 + b2 +c3;
    std::cout << " Great! so your results were " << sum2 * x<< "";
}

when i run it if i only type 2 numbers and press enter it doesn´t show the output cause it waits for me to add the 3rd value. I want to be able to put between 1 and 3 numbers, but i want the program to give a value of 0 if i didn´t input the value.

Since you don't know how many numbers are being entered, you should read the entire line first, and then extract numbers from that line as needed, eg:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    // weekly accountability
    std::cout << " ... Please write down the numbers\n";

    std::string line;
    std::getline(std::cin, line);

    std::istringstream iss(line);

    double num, sum = 0.0;
    while (line >> num) {
        sum += num;
    }

    double x = 0.66;
    std::cout << " Great! so your results were " << sum * x;

    return 0;
}

Otherwise, you can just keep reading from std::cin directly until the user types in their platform's EOF sequence (or enters bad input), eg:

#include <iostream>

int main() {
    // weekly accountability
    std::cout << " ... Please write down the numbers\n";

    double num, sum = 0.0;
    while (std::cin >> num) {
        sum += num;
    }

    double x = 0.66;
    std::cout << " Great! so your results were " << sum * x;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM