[try Beta version]
Not logged in

 
 
structures in c++

May 10, 2015 at 9:22am
for the below code, given input :
a
b
c
d
e
f
g
h
i
j
k
l

the output comes out to be:
a
b
c
d
e
f

while i expected it to be:
b a
d c
f e
h g
j i
l k

what mistake am i making?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdio>

using namespace std;

struct work{
	char employee;
	char manager;
}list[6];

int main(){
	int i;
	for (i=0;i<6;i++){
		scanf("%c",&list[i].employee);
		scanf("%c",&list[i].manager);
	}
	for(i=0;i<6;i++){
		printf("%c %c",list[i].manager,list[i].employee);
	}
}

May 10, 2015 at 9:31am
I guess the second scanf() picks up the newline character you type when you hit enter to confirm input.
May 10, 2015 at 10:41am
yeah!!
you are right.
the code is working fine for the input:

abcdefghijkl

the code is taking newline and spaces as input!! i am unable to understand the working of the code. how can i change that?
May 10, 2015 at 10:48am
One solution is validate input and keep scanning if it's invalid.
http://www.cplusplus.com/reference/cctype/isalpha/ may be useful.
May 10, 2015 at 10:53am
that will be fine but why is scanf taking the input as a string? as is specified by %c it should take only one character input and a space or enter should end the input.
May 10, 2015 at 11:02am
well i got the answer.
refer the link for the solution
https://gsamaras.wordpress.com/code/caution-when-reading-char-with-scanf-c/
May 10, 2015 at 11:06am
I don't know precisely the inner workings of io streams, so you may want to ask someone more qualified or do more research.
AFAIK when you hit enter anything you wrote is copied into a buffer and scanf/cin read stuff from that buffer.
The "%c" format string is telling scanf to read a single character from the buffer, but anything else is left there ready to be read.
When the buffer is empty, scanf will pause the program waiting for a newline character to write to the buffer and resume reading.

A space is not a newline so it won't unblock the program.
Last edited on May 10, 2015 at 11:07am
Topic archived. No new replies allowed.