-2

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.
Noooo
  • 68
  • 7

4 Answers4

1

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 : ");
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
M. Yousfi
  • 578
  • 5
  • 24
1

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.

Ron
  • 14,674
  • 4
  • 34
  • 47
0

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;
}
AVI
  • 1
  • 1
0

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;
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93