cin vs getchar()

i was trying to make a program it worked good with cin but not with getchar please tell.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*Program to read a character and display its next character in the ASCII list*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
    char ch,Next,ch1;
    do
    {
        cout<<"\nEnter any character : ";
        ch=getchar();
        Next=ch+1;
        cout<<"\nThe next character is : ";
        putchar(Next);
        cout<<"\nWant to enter more(y/n)";
        ch1=getchar();
    }
    while(ch1=='y'||ch1=='Y');
    cout<<"\n";
    system("pause");
    return 0;

The above program instead of taking the value of ch1 terminates the loop itself .While the following program with cin works fine.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*Program to read a character and display its next character in the ASCII list*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
    char ch,Next,ch1;
    do
    {
        cout<<"\nEnter any character : ";
        cin>>ch;
        Next=ch+1;
        cout<<"\nThe next character is : ";
        putchar(Next);
        cout<<"\nWant to enter more(y/n)";
        cin>>ch1;
    }
    while(ch1=='y'||ch1=='Y');
    cout<<"\n";
    system("pause");
    return 0;
}
std::cin skips white space getchar does not.

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
/*Program to read a character and display its next character in the ASCII list*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
    char ch,Next,ch1;
    do
    {
        cout<<"\nEnter any character : ";
        ch=getchar();
        std::cin.ignore();
        Next=ch+1;
        cout<<"\nThe next character is : ";
        putchar(Next);
        cout<<"\nWant to enter more(y/n)";
        ch1=getchar();
        std::cin.ignore();
    }
    while(ch1=='y'||ch1=='Y');
    cout<<"\n";
    system("pause");
    return 0;
}
By default, cin ignores all whitespace. getchar() does not, so the prompt asking for 'y' or 'n' is actually reading a newline '\n', which fails the loop condition.

Hope this helps.
the program given by
Yansoon
works as i want the program to so std::cin.ignore() is for ignoring a blank space or ignoring everything irrelevent?
And yes, thanks to both of you
cin.ignore();

is identical to

getchar(); (notice: no assignment to a variable!)
thanks got it
Topic archived. No new replies allowed.