user6490375 user6490375 - 3 months ago 17
C++ Question

Unexpected output using scanf() and printf() in C++

I have written the following simple code snippet:

#include<cstdio>
#include<iostream>
using namespace std;

int main()
{
int w, h;

scanf("%d %d", &w, &h);

char shop[h][w];
for(int i=0; i<h; i++)
for(int j=0; j<w; j++)
scanf("%c", &shop[i][j]);
//cin>>shop[i][j];

for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
printf("%c", shop[i][j]);
//cout<<shop[i][j];
printf("\n");
//cout<<"\n";
}

return 0;
}


On passing the input as below:


4 3

X1S3

42X4

X1D2



I expect the output to be the same, because I am not modifying anything in the code. However, when I print it, I get the following output:


X1S

3

42

X4

X



However, on replacing
scanf()
and
printf()
with
cin
and
cout
correctly generates the required output. Any inputs to where I might have gone wrong?

Link to code with
printf()
: http://ideone.com/NvHQUl

Link to code with
cout
: http://ideone.com/PQWe9R

Update:
h
denotes the number of rows; while
w
denotes the number of columns.

Answer

The %c format specifier in scanf reads and assigns the next character including whitespaces and newlines. Per scanf specs:

All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters (determined as if by calling isspace) before attempting to parse the input.

Therefore scanf("%c", &shop[i][j]); will read the newline at the end of each line of input as a regular character, and assign it to some element in the array, which explains the printf output.

To skip over whitespace use scanf(" %c", &shop[i][j]); instead (note the additional     space before %c).

Comments