Quick Intro:
The problem will probably be obvious, but I just started programming a week ago. I'm exploring different uses for functions, and wanted to create one that would output the highest integer a user inputs. I know there are specific functions that might do this, but I haven't learned those yet, and I still want to understand the fundamental problem behind my code.
Problem/Question: Are int functions limited to numeric return values?
The code works fine if the function is returning a specific value (any situation where one of the variables "x" "y" or "z" is greater than the others. However, if any values are equal and it returns the "cout" it also outputs either a string of numbers at the end or "0"--depending on how the variables are input (the code below spits out "134519712"--but if I allow user input and just make the function something like "max(1,2,2)" it outputs zero.
I tried searching (Google, this forum, and other forums) to see if it's just not acceptable to use "cout" for int functions, but can't find any specific guidance, and don't want to start making assumptions so early on.
Thanks in advance and sorry for the easy question. Code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//Function to determine the max value from a user input.
int max(int x, int y, int z){
if ((x>y) && (x>z)){
return x;
}
else if ((y>x) && (y>z)){
return y;
}
else if ((z>x) && (z>y)){
return z;
}
else {
cout << "\nHmm. Looks like one or more numbers are equal in value.\n";
//The problem is, after this, there's always a "0" or "134519712"--depdending on how the variables are input. Can an int function output a cout statement without returning a value?
}
}
int main(){
int a;
int b;
int c;
string input;
cout << "Type in number 1 of 3:\n";
getline (cin,input);
stringstream(input) >> a;
cout << "\nType in number 2 of 3:\n";
getline (cin,input);
stringstream(input) >> b;
cout << "\nType in number 3 of 3:\n";
getline (cin,input);
stringstream(input) >> c;
cout << "\nThe highest number you gave me was... \n";
cout << max(a,b,c);
cin.get();
}
|