For this content of the file/stdin:

a 3
W 10
A 100
, 10
k 7
. 3
I 13

I have written the following code

while (k-- > 0)
{			
		scanf(" %c %d",&c, &p);
		printf("c: %d p: %d\n",c,p);
}

if I change the format string in scanf from %c to %d I get the value of c and p as 0. Now the thing is that the character input can be unsigned character so I was wondering how to mention the format string in scanf to take unsigned character. I mean the c can be of type unsigned char. I tried %hh and %u but both gives c the value of 0. Morover, if we have a string consisting of unsigned characters. Then how to take input of it? declaring a string as

unsigned char str[1000]
and passing str to str to fgets gives compile error.

Recommended Answers

All 6 Replies

well... your question is kind of hard to follow but, i think your confusion might be in your while() statement.

for instance: if k=1 , and then you say while (k-- > 0) the statement k-- > 0 is true, because k post-decremented is evaluated while k=1 but then the post decrement occurs and the rest of the block is evaluated while k=0

scanf() is hard to use at the best of times.

%c just makes it horrible in the extreme. Any random space on the input will screw you up.

fgets( buff, sizeof buff, stdin );
sscanf( buff, "%c%d", &myChar, &myInt );

Can you explain the question more clearly.
Also if you can, post the sample input and output

I posted the input already. Let's recapitulate:

1.
      a 3
   2.
      W 10
   3.
      A 100
   4.
      , 10
   5.
      k 7
   6.
      . 3
   7.
      I 13

The problem is not with the while loop. This a sample output. The output will most likely be passed from file:

./a.out < input.txt

So there might be some characters which has value > 128. My question is I am facing trouble taking unsigned characters. To be more clear, I am taking input considering the possibility the characters being both within 127 and within 255 even though the input shown here is only within 127. And as you see the input line consists of a character and an integer.

Now the trouble is if I scanf then %d is not working (c contains value 0). If I use fgets then it gives complie time error if I pass an array of unsigned characters (ie unsigned char str[]) because its signature calls for signed character array. Even if I take the whole input line as a string, then use sscanf there is again the problem of format string (ie %c or %d).

So to summarize, the input consists of a line consisting of an **unsigned char** and an int. The format string %d for character in scanf gives 0. fgets does not work with unsigned character array.

So use %u for unsigned decimal instead of %d for signed decimal. And declare your variable as unsigned .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.