-
I am a beginner to, but try this:
I am a beginner too, but try this: (Use #'s instead of a&Z)
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int number;
char ch;
do
{
cout<<"Please enter a number"<<endl;
cin>>number;
if(!(number>='1' && number<='100'))
sum = sum + number;
else
break;
cout<<"Do you want to enter another number(y/n)"<<endl;
cin>>ch;
}while(ch!='n');
cout<<"the total characters entered is "<<sum<<endl;
return 0;
}
-
Re: I am a beginner to, but try this:
Paul wrote in <38efbaaf$1@news.devx.com>:
>
>I am a beginner too, but try this: (Use #'s instead of a&Z)
We all start somewhere...
>
>#include <iostream>
>using namespace std;
>
>int main()
>{
> int sum = 0;
> int number;
> char ch;
> do
> {
> cout<<"Please enter a number"<<endl;
> cin>>number;
//if a number was not entered, cin.fail() is true.
>
> if(!(number>='1' && number<='100'))
//the quotes here aren't going to do what you expect
//'1' !=(int)1 (on most implementations
> sum = sum + number;
> else
> break;
> cout<<"Do you want to enter another number(y/n)"<<endl;
> cin>>ch;
> }while(ch!='n');
try changing the above loop to:
while (cout<<"Please enter a number"<<endl,cin>>number){
//or more simply
while (cin>>number){
sum+=number;
cout<<"Do you want to enter another:"<<endl;
cin>>ch;
if (ch !='n') break;
//I forget if you should use a cin.ignore to remove the newline
}
> cout<<"the total characters entered is "<<sum<<endl;
> return 0;
>}
>
A more robust way of doing this would be to read the input as a string (or
char array) and parse it to extract the valid data (but maybe overkill.)
--
regards,
nick
-
Re: I am a beginner to, but try this:
nick wrote in <8F119F700sdklj98dm4@209.1.14.192>:
Of course, we all need enough sleep as well...
>
>try changing the above loop to:
>
> while (cout<<"Please enter a number"<<endl,cin>>number){
> //or more simply
> while (cin>>number){
> sum+=number;
> cout<<"Do you want to enter another:"<<endl;
> cin>>ch;
// if (ch !='n') break;
//the above should have been:
if (ch!='y') break; // or
if (ch=='n') break;
> //I forget if you should use a cin.ignore to remove the
newline
> }
--
regards,
nick
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks