Hello. This isn't really a problem, but more so I'm confused why something happens.
Basically, I'm making a program that will automatically factor any polynomial. I figured I'd want the degree of the polynomial before I try to factor it, so I'm trying to safely get an integer variable "degree" safely (so it will not, under any circumstances, give me an error, no matter what I type in- even characters). Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int degree;
string inputstr;
cout << "Degree of function: ";
getline(cin,inputstr);
while(true)
{
stringstream mystream(inputstr);
if (mystream >> degree){break;}
cout << "\"" << inputstr << "\" is not a number.\nDegree of function: ";
getline(cin,inputstr);
}
return 0;
}
|
(P.S.: feel free to comment on my code. I'm open for improvements and learning new things.)
In line 14, you see
stringstream mystream(inputstr);
. However, if I move this line down to below what is currently line 17 (
getline(cin,inputstr);
), it won't work anymore. I played around a bit with the code and displaying what the variables contain, and I found out that the
mystream
variable contains 0 when the program runs line 15 if it's placed below
getline(cin,inputstr);
. However, if it is placed where it is now (line 14 from the above code), it seems to contain (what I would guess to be) a hexadecimal memory address (0x28fdc4). At the end of the while() loop, does something happen to the stringstream variable that causes it to be set equal to 0?
I guess I'm just confused about what a stringstream is and how it works. Does anyone know of a good tutorial on streams? I didn't find anything in this website's tutorial page (
http://www.cplusplus.com/doc/tutorial/ ), which is what I usually go to if I don't understand or if I forget something.
Thank you for your time, and if you need any other information, please ask.