Reputation: 317
Hi I am trying to read input from the user once and then pass this value into two different types of variables is this possible?
I need the value to be passed into an integer variable which is required for calculations and also a string so I can add the data to the formatted date which is a string variable.
Here is he code which I have tried which doesn't work.
cin >> daymonth,dayofmonth;
Any help would be greatly appreciated, I am programming in OOP if this is of any relevance.
Upvotes: 1
Views: 8434
Reputation: 47854
You can overload <<
#include<sstream>
//..
class X{
int daymonth;
std::string dayofmonth;
friend std::istream& operator >> (std::istream& is, X& m)
{
is >> m.daymonth;
std::stringstream ss;
ss << m.daymonth;
m.dayofmonth = ss.str();
return is;
}
friend std::ostream& operator << (std::ostream& os, const X& m)
{
return os << m.daymonth << ":" << m.dayofmonth;
}
};
And then
X x;
std::cin >> x;
std::cout << x;
Upvotes: 0
Reputation: 57749
Try copying / assignment:
cin >> daymonth;
dayofmonth = daymonth;
In the performance of your program, using multiple lines or multiple statements is negligible.
Concentrate on making the program work correctly and robustly.
Edit 1: dayofmonth is a string.
cin >> dayofmonth;
istringstream s(dayofmonth);
s >> daymonth;
Upvotes: 0
Reputation: 31685
You cannot read into two variables simultaneously. The type of variable that you read into determines how far to read. For example, reading into a string stops at white space while reading into an integer stops at the first non-integer character. Reading into two variables simultaneously would make it ambiguous where the next reading operation starts.
Read into an integer and then convert the integer to a string (e.g. using std::to_string
).
Upvotes: 3