Hi. I just installed code::blocks to replace dev-C++. I have a program that runs fine when compiled with dev-C++ but not with code::blocks. In particular, this section of my code seems to be causing the problem:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<sstream>
usingnamespace std;
int check1=0;
int main()
{
int Check(string a);
.
.
.
MaxTemp=Check("maximum");
cout<<MaxTemp;
.
.
.
}
int Check(string a) /*This function checks to see that a character input
consists only of digits and is a multiple of 50, and if so, returns the string
as an integer*/
{
string b,c;
int x;
double y,z;
cout<<"\nEnter the "<<a<<" temperature: ";
stringstream ss;
while(1==1)
{
getline(cin,b);
for(i=0;i<b.size();i++)
{
if(isdigit(b[i]))
check1=check1+1;
}
if(check1==b.size())
{
check1=0;
ss<<b;
ss>>y;
cout<<b<<endl;
z=y/50;
ss.clear();
ss<<z;
ss>>c;
cout<<c<<endl;
ss.clear();
for(i=0;i<c.size();i++)
{
if(c[i]=='.')
check1=check1+1;
}
if(check1==0)
{
ss<<b;
ss>>x;
cout<<x<<endl;
return x;
break;
}
else
cout<<"\n Invalid Entry.\n\n"<<"Enter the "<<a<<" temperature: ";
}
else
cout<<"\n Invalid Entry.\n\n"<<"Enter the "<<a<<" temperature: ";
check1=0;
}
}
I included some cout commands to try to find out where the problem is occurring. Let's say the user types 650 as the temperature input. This is what the console window prints out:
650
13
650
10227456
The last number changes each time I run the program. I don't understand what's going on. The value x in the function is correct, but when I return it to the main function and assign it to MaxTemp, it changes. Please help.
EDIT: you were right, i first broke out of the loop, then return x outside the loop. Now it works fine. Odd. Not really sure why this was happening. Thanks for the help though!
Not sure what you mean. I prompt the user for input before the loop starts, then I include the getline in the loop. The loop continues infinitely and the user is continuously asked to enter a valid temperature until a correct temperature is entered, then the loop breaks and the function returns the temperature. Is that not the same as "prmpting for input and actually getting the input"? The program seems to be working fine now, but I'd still like to know what you mean, in case there is some hidden problem. Thanks. Also, can anyone tell me why the function returned a garbage value when I included the return inside of the loop?
Also, can anyone tell me why the function returned a garbage value when I included the return inside of the loop?
The return in the loop still worked fine for me using portable CodeBlocks EDU edition.
With your original code maybe see what is in MaxTemp before you assign Check's result to it.
If MaxTemp garbage is the same before and after then maybe the return value is OK but it is not being assigned to MaxTemp or something?