Problem in a program??

Pages: 12
HellO!
So, I made a simple program that says if the no. is even or odd..
The problem is that when i write any letter , it says "even".. lol
Could anyone tell me what's the problem with the code?
Thnx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main ()
{
    int x;
    cin>>x;
    if (x%2==0)
    cout<<"The number is Even"<<endl;
    else if (x%2!=0)
    cout<<"The number is Odd"<<endl;
    else
    cout<<"Error"<<endl;
    system ("PAUSE");
    return 0;
       
}
> The problem is that when i write any letter , it says "even"
¿what do you want/expect to happen?
If you input a letter, the reading fails and `x' remains uninitialized.
If you enter a letter, this cin operation will fail cin>>x;
When that happens, x retains its previous value. Since it was not initialised, it might be either even or odd.

You might trap it like this:
1
2
3
4
5
6
    while (!(cin >> x))
    {
        cout << "invalid input, please try again" << endl;
        cin.clear();            // clear error flags
        cin.ignore(1000, '\n'); // clear invalid input from buffer
    }

Incidentally, the if statements are overdone, This test if (x%2==0) can only be either true or false, so you just need a plain else to catch the alternate condition, and the third part is pointless as it can never be executed.
Last edited on
closed account (EwCjE3v7)
You also forgot curly brackets "{}"
Example
1
2
3
4
5
6

If (){

}else{

}
Last edited on
Braces are required when more than one statement is required to be controlled by the if / else. On other occasions they don't do any harm, but aren't strictly necessary.
Braces are required when more than one statement is required to be controlled by the if / else. On other occasions they don't do any harm, but aren't strictly necessary.
They may not be necessary, but it's a good idea to put them in anyway. I've lost count of the number of times I've seen bugs introduced into a program, because people decide to add a second line to a conditional block and forget to put the braces around it, e.g. changing:

1
2
3
4
5
6
7
8
9
bSuccess = myFunc();
if (!bSuccess)
  return;

// Successful, so carry on doing stuff
bSuccess = myOtherFunc();

// etc... 


to:
1
2
3
4
5
6
7
8
9
10
bSuccess = myFunc();
if (!bSuccess)
  std::cout << "myFunc was not successful" << std::endl;
  return;

// Successful, so carry on doing stuff
bSuccess = myOtherFunc();

// etc... 

It's much safer to put the braces in to start with.

(Edit: I edited the code to make the point I was making clearer.)
Last edited on
I think because every letter in ASCII has a similar binary form
http://en.wikipedia.org/wiki/ASCII
@MikeyBoy Broadly speaking I agree with you and tend to follow such 'safety first' approaches in my own code. Though when addressing an audience of beginners it can be useful to distinguish between what is good practice and what is the basic syntax of the language.

@Yemeni Cpluspluser - Sorry, I don't understand the significance of your post in this thread.
> Broadly speaking I agree with you and tend to follow such 'safety first' approaches in my own code.

I don't. Introducing unnecessary (horizontal or vertical) white space impairs readability. I write single statement if blocks this way (on the same line as the if/else):

1
2
if( some_condition ) do_this() ;
else do_something_else() ; 


IMHO, it is far more readable than:
1
2
3
4
5
6
7
8
if( some_condition ) 
{
    do_this() ;
}
else 
{
    do_something_else() ; 
}


That is probably because I generally don't write code targeting the lowest common denominator. People who want to modify the code are expected to know how to write basic control structures correctly.
I was talking very broadly about how I would approach coding regardless of the language in which it was written. Perhaps I've spent too long maintaining other people's code.
@Chervil
Broadly speaking I agree with you and tend to follow such 'safety first' approaches in my own code. Though when addressing an audience of beginners it can be useful to distinguish between what is good practice and what is the basic syntax of the language.

I agree completely! I wasn't trying to contradict you, I was just expanding a little more on the topic.

@JLBorges
That is probably because I generally don't write code targeting the lowest common denominator. People who want to modify the code are expected to know how to write basic control structures correctly.

That's fine, if your priority is feeling smug about what a great programmer you are, and sneering those who make mistakes. As a professional software developer, my priority is writing robust, maintainable code, and that includes adopting good practices that defend against the accidental introduction of bugs.

In my experience, the most terrible type programmer of all is the one deluded enough to think neither they nor their colleagues will ever make a mistake. Everybody has a bad day every now and then.

(I would also disagree with your assertion of which of your two code snippets is more "readable", but that's another topic...)
> As a professional software developer, my priority is writing robust, maintainable code,

You are being asinine if you believe that you are the great'professional software developer' whose blind beliefs constitute the one and only true way in which code must be written.

Mono coding guidelines:
Avoid using unnecessary open/close braces, vertical space is usually limited:
good:
1
2
if (a)
	code ();

bad:
1
2
3
if (a) {
	code ();
}

http://www.mono-project.com/Coding_Guidelines

There are innumerable others; for instance
GNU: http://www.gnu.org/prep/standards/standards.html#Formatting
VCMI: http://wiki.vcmi.eu/index.php?title=Coding_guidelines#Where_to_put_braces

In my experience, the most terrible type programmer of all is the one deluded and opinionated enough to think that his blind, unreasoned, begotted beliefs about programming constitute a universal religion.


> (I would also disagree with your assertion of which of your two code snippets is more "readable", but that's another topic...)

Save yourself the trouble because I don't care in the least whether you agree with me or not. I have utter contempt for your opinions.
I'm not interested in who is right or who is wrong. What is pretty clear from experience is that under certain usage conditions, a particular style of code will be more suitable. There isn't a 'one size fits all'.
@Chervil
I mean it treats the character "if alphabets" as a number according to the ASCII table

Here is a program I did now
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;


  int main()
  {
      cout<<"Enter a letter to see it in ASCII " ;
      char ASCII;
      cin >> ASCII;
      int num = ASCII ;
      cout <<"The number is " << num ;
      return 0;
  }



EDIT ::

No, I think I was wrong, it treats every character assigned to int as number 0 in mingw compiler and as 2147483648 int dev cpp which is even .
Last edited on
@Yemeni Cpluspluser
The code you posted does output the ASCII code of the character.

However in the original code:
1
2
    int x;
    cin >> x; 

... if the user types a character which is not an integer, the input fails and that character remains waiting in the input buffer.

The values of 0 and 2147483648 are simply whatever random value happens to be stored in the uninitialised variable. It isn't truly random, it will simply be whatever value is already in the particular memory location used for the variable x.
You are being asinine if you believe that you are the great'professional software developer' whose blind beliefs constitute the one and only true way in which code must be written.
In my experience, the most terrible type programmer of all is the one deluded and opinionated enough to think that his blind, unreasoned, begotted beliefs about programming constitute a universal religion.

Nowhere have I stated that this is the "one true way". In fact, I've argued against religious one-true-wayism on this forum and in others. What I have done is made some recommendations, and clearly (I hope) explained my reasons as to why I think my recommendations are worth adopting. I've also, apparently, had the tenacity to disagree with you, which appears to have prompted an explosion of ire.

You're grossly misrepresenting my position here. Please don't do that. It's dishonest, and it adds nothing of value to the discussion.

Mono coding guidelines:
Avoid using unnecessary open/close braces, vertical space is usually limited:

I've worked in environments where vertical space is limited - small, old-fashioned, low-resolution monitors, etc. In those conditions it has been the case that the benefits of forgoing the braces for single-line blocks outweigh the benefits of putting them in, and I'll quite happily adopt that practice under such conditions.

However, I don't think that "vertical space is usually limited" is an accurate description of the circumstances of most people programming in 2013. Monitors these days tend to be cheap, large and high-resolution, and even laptops have screen sizes and clarity that I would have killed for when I started out in this industry.

In any case, it's a stronger argument than just expecting nobody to ever make a mistake when maintaining code.

I'd also argue that a beginner (and, remember, we are in the Beginners forum here) is more likely to make the kind of mistake that you or I would catch in an instant, and that adopting practices that protect against such mistakes should therefore take an even higher priority.

I appreciate that these are matters of opinion, and I'm certainly happy to consider good arguments for adopting alternate practices. I'm just not convinced that saving a bit of vertical space is, under usual programming conditions, a strong argument for abandoning robustness. Nor is "I expect people never to make a mistake".
> I've also, apparently, had the tenacity to disagree with you, which appears to have prompted an explosion of ire.

Sow the wind and reap the whirlwind. You are like the junior school bully who picks on a child he perceives as smaller and weaker, and will meekly submit to his oppression; and then runs crying 'mummy' when someone stands up to him.


> What I have done is made some recommendations ...

What I had done was state the way in which I write code for my intended audience, which I had made very clear in my post. Which happened to disagree with your 'recommendation'. And you then started on the path of an explosion of ire; a personal attack on someone who dared to disagree with you in the midst of a technical discussion.


> I appreciate that these are matters of opinion,

No, you don't. Your original response to a technical disagreement was odious, and your attempt at sweeping it under the carpet now is both pathetic and disgusting.
@JLBorges
Avoid using unnecessary open/close braces, vertical space is usually limited:


Empty lines are very important formatting elements.

For example the code shown above (it si not inportant what it does)

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;


  int main()
  {
      cout<<"Enter a letter to see it in ASCII " ;
      char ASCII;
      cin >> ASCII;
      int num = ASCII ;
      cout <<"The number is " << num ;
      return 0;
  }


would look much better if there would be empty lines

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;


int main()
{
      cout<<"Enter a letter to see it in ASCII " ;

      char ASCII;
      cin >> ASCII;

      int num = ASCII ;
      cout <<"The number is " << num ;

      return 0;
}


@JLBorges

good:
if (a)
code ();

bad:

if (a) {
code ();
}


IMO the both styles are bad. First of all the human being as any other predator has no peripheral sight. So it would be much better if braces would be vertically aligned. So instead of

1
2
3
if (a) {
	code ();
}


it would be much better to write

1
2
3
4
if (a) 
{
	code ();
}


I do not consider this code as bad.

As for this code snip assuming that code() is some function

1
2
if (a)
	code (); 


I would rewrite it in one line

if (a) code ();

provided that this statement is not followed by an else statement. Otherwise I would consider the possibility to use braces.

Last edited on
> Avoid using unnecessary open/close braces, vertical space is usually limited:

>> Empty lines are very important formatting elements.

> IMO the both styles are bad.

> etc.


You are entitled to your opinions.

Just as much as the Mono developers are entitled to theirs.

No more, and no less.

In the end, that is all that it is; your personal opinion.
While it may be worth a great deal to you, equally it may be worth nothing to someone else.

(See how nice the post looks with lots of vertical white spaces in between!)
> a human being as any other predator has no peripheral sight
1
2
3
4
5
6
7
8
if (a)
{//<- when looking at this
	code (); //I can't see this
}

if (a) {
	code ();
}//go up till there is no whitespace 


1
2
3
if (!bSuccess)
  std::cout << "myFunc was not successful" << std::endl;
  return;
there wouldn't be a problem if they don't indent manually.
Pages: 12