Okay guys . This is an assignment for my class . So far i managed to complete most of them but im having problems with this question :
9.)Write a program that continuously accepts and computes the sum of a number. If the user enters quit the looping stops. The program should be able to display the highest number upon termination of the loop
ex:
Enter a number: 12
Sum: 12
Enter number3: 10
Sum: 22
Enter number5: quit
The highest number is 12
Process completed.
(note: still a beginner )
could someone explain to me please ? \
thanks in advance .
#include<iostream>
usingnamespace std;
int main()
{
char value1,value2;
int sum;
value2=0;
do{
cout<<"Please enter a value or type quit : ";
cin>>value1;
if (value2 <= value1)
{
value2=value1;
}
sum+=value1;
}while(value1!="Quit");
cout<<"Highest number is : "<<value2<<"\n";
cout<<"The sum is : "<<sum;
cout<<value2;
system ("pause");return 0;
}
nevermind i thought it would work .
help and an explanation plz ><;\
thanks in advance
Yeah, that's a beginner problem you can't solve alone so I'll help ;)
value1 is of type char which can hold 1 character
"Quit" is not of type char, it consists of 4 (5) characters, it's of type const char*, which is a pointer type.
you can't compare a value of type char with a value of a pointer type, that's the problem.
To solve the problem your input should read in a std::string, then compare and if it's the text "Quit" and then convert it to an integer.
I guess you didn't do that in your course so far so here's a solution I can give you that will look like you did it yourself:
#include<iostream>
#include <string>
#include <cstring>
usingnamespace std;
int main()
{
string str;
int biggest;
int sum;
while(1) {
cout << "Please enter a value or type \"Quit\" : ";
cin >> str;
if(str == "Quit")
break;
int value = atoi(str.c_str());
if(value > biggest)
biggest = value;
sum += value;
}
cout<<"Highest number is : "<<biggest<<"\n";
cout<<"The sum is : "<< sum;
system ("pause");return 0;
}
#include<iostream>
#include<cstring>
#include<string>
usingnamespace std;
int main ()
{
string pnum;
int pnum2,sum;
cout<<"Please enter a value : ";
getline (cin,pnum);
do
{
int value = atoi(pnum.c_str());
if( value > pnum2 )
{
pnum2=value;
}
sum+=value;
cout<<"Please enter a number or type quit: ";
getline (cin,pnum);
}while (!pnum="Quit" || !pnum="quit" || !pnum="QUIT");
cout<<"Highest number is "<<pnum2<<"\n";
cout<<"Sum is "<<sum<<"\n";
system ("pause");return 0;
}