I want to assign the input of the user added by a value to a variable in a single line . Is there anyway that I could possibly do this?
std::cout << "Please enter a number";
std::cin >> number; //thinking of adding 10 to number in this same line.
I want to assign the input of the user added by a value to a variable in a single line . Is there anyway that I could possibly do this?
std::cout << "Please enter a number";
std::cin >> number; //thinking of adding 10 to number in this same line.
There is no built-in function for this in C++, but you can write it:
int input(string prompt)
{
int x;
cout << prompt;
cin >> x;
return x;
}
Then you can call it, let say in main function like this:
int main()
{
int num = 10 + input("Please enter a number to add to 10 : ");
}
As others have pointed out in the comments you can write a function of your own and utilize the std::stoi function:
#include <iostream>
#include <string>
int input(const std::string& s){
std::string tempstr;
std::cout << s;
std::getline(std::cin, tempstr);
return std::stoi(tempstr);
}
int main(){
int num = 10 + input("Please enter a number to add to 10:");
std::cout << num;
}
Error checking omitted for simplicity.
The question is quite of a curiosity.One answer can be like mentioned above like you can develop a function "input" which returns the intake value . But if you want in in one liner without any function.
enter code here
#include<iostream>
using namespace std;
int main()
{
int x,num;
if (cout<<"enter new number") if(cin>>x) num=10+x;
cout<<num;
}
You can use something like this, without extra variables nor functions (although a function is the best way):
#include <iostream>
using namespace std;
int main()
{
int num = (cout << "Input: ") && (cin >> num) ? num + 10 : 0;
cout << num;
return 0;
}