argument to number C++
#include <iostream>
#include <sstream>
int main() {
std::string input;
std::cout << "Enter a number: ";
std::cin >> input;
std::istringstream iss(input);
int number;
iss >> number;
if (iss.fail()) {
std::cout << "Invalid input! Please enter a valid number.";
} else {
std::cout << "The number entered is: " << number;
}
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library for basic input and output operations.#include <sstream>
: Includes the string stream library for handling string-based input/output operations.int main() { }
: The main function where the program execution begins.std::string input;
: Declares a string variable namedinput
to store the user's input.std::cout << "Enter a number: ";
: Outputs a message asking the user to enter a number.std::cin >> input;
: Reads user input from the standard input (keyboard) and stores it in theinput
variable.std::istringstream iss(input);
: Creates a string stream objectiss
and initializes it with the content of theinput
string.int number;
: Declares an integer variable namednumber
to store the converted number.iss >> number;
: Attempts to extract an integer value from the string streamiss
and store it in thenumber
variable.if (iss.fail()) { } else { }
: Checks if the extraction was successful.std::cout << "Invalid input! Please enter a valid number.";
: If the extraction fails (i.e., invalid input), outputs an error message.std::cout << "The number entered is: " << number;
: If the extraction is successful, outputs the entered number.return 0;
: Indicates successful program execution and terminates themain
function.