"printf" and "scanf", something wrong with stream - c

So here is my code.
int main(int argc, char* argv[])
{
char c;
size_t place;
while (1) {
scanf("%c %u", &c, &place);
printf("%c\n", c);
}
return 0;
}
When I compiled and ran program I expected to see terminal like this:
a 1
a
b 2
b
c 3
c
But I saw this:(some extra '\n')
a 1
a
b 2
b
c 3
c
Please help me find what I did wrong.

You may try like this:
scanf(" %c %u", &c, &place);
^^--Add space here
instead of
scanf("%c %u", &c, &place);

printf("char is %c\n", c); Adding some string before printing the received character will helps you to understand more clearly why its behaving like this. After your input some blank spaces or new line is entered, that is used in the next scanf. You can even print the ascii value of the charater like printf("char is %d, %c", c, c); and serach the ASCII value in the ASCII table, to understand exactly which value (blanks or new line or tab) scanf has received mistakenly.
Keeping blankspace as first character in format string of scanf will helps to skip all leading blanks(including tabs and newline). Like scanf(" %c %u", &c, &place);

Related

loop 2 taking input automatically

My code is behaving weirdly. In loop 1 it is working perfectly but in loop 2 it is automatically printing ASCII value 10. please help!.
#include<stdio.h>
int main(){
char c;
int loop =1;
do{
printf("\nLoop = %d\nWrite character of which you want to find acii values: ", loop);
scanf("%c", &c);
printf("\nASCII value of %c is %d.", c, c);
loop++;
}while(c != 'Z');
printf("\n******END*****");
return 0;
}
10 is ASCII for newline. You are reading whitespace, which you can avoid by using
scanf(" %c", &c);
Note the additional blank before the character specifier. It instructs scanf to ignore white space.

scanf formatted input does not apply to first character scanned

I'm trying to write a program that outputs non-vowel characters (without if statements and using formatted scanf input). The code I currently have does not apply the %*[] ignored characters to the first %c character scanned, but the restriction applies for the other characters. For example, "Andrew" becomes "Andrw" instead of "ndrw". I'm suspecting this could be due to the %c at the beginning. Could someone help me please? :)
#include <stdio.h>
#include <string.h>
int main(void) {
char c;
while (scanf("%c%*[aeiouAEIOU]", &c) == 1)
printf("%c", c);
return 0;
}
The scanf formats are matched in order so %c is matched first for the A. You need to use 2 separate scanfs for this, or precede the loop with the initial-vowel eating scanf:
scanf("%*[aeiouAEIOU]");
while (scanf("%c%*[aeiouAEIOU]", &c) == 1) {
printf("%c", c);
}
The question is is this any clearer and better than
int c;
while ((c = getchar()) != EOF) {
if (! strchr("aeiouAEIOU", c)) {
putchar(c);
}
}
I have an opinionated answer...

Unable to understand - reading characters from files in C

I have just started learning file handling in C, and wondered if I could perform mathematical calculations by reading input from a file, here is the code for just reading the characters and displaying on the console :
int main(void)
{
FILE *p;
char a, b, c, ch;
p = fopen("numbers.txt", "a+");
while((ch = getc(p)) != EOF)
{
fscanf(p, "%c %c %c\n", &a, &b, &c);
printf("%c %c %c\n", a, b, c);
}
fclose(p);
return 0;
}
numbers.txt contains (with a space before each character) :
2 + 3
5 + 6
6 + 7
output obtained is :
2 + 3
+ 6
+ 7
I am unable to understand why first line output is as expected but second and third line have missing character, even though new line is given after each expression in numbers.txt.
An additional character is being scanned at the beginning of each iteration of your while loop
while((ch = getc(p)) != EOF)
Try making the fscanf() statement as the condition for your while loop and check for its return value. According to cplusplus.com:
On success, the function returns the number of items of the argument
list successfully filled. This count can match the expected number of
items or be less (even zero) due to a matching failure, a reading
error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while
reading, the proper indicator is set (feof or ferror). And, if either
happens before any data could be successfully read, EOF is returned.
So try changing your while condition to anyone of the following:
while (fscanf(p, " %c %c %c", &a, &b, &c) != EOF)
or
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3)
Using whitespace in the scanf format specifier, like you do with \n, matches any amount of whitespace. The \n and the leading space on the next line are consumed, causing getc to remove the first digit instead of the leading space.
I’d skip getc entirely, as #BLUEPIXY suggested:
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3) {
printf("%c %c %c\n", a, b, c);
}

Work With Char Using If else in C Language

Whenever I use if Statement to make a decision by comparing a character using char and %d, then it results in false always.
example:
#include<stdio.h>
#include<conio.h>
int main(void) {
int a, b;
float r;
char op;
printf("Enter 1st num : ");
scanf("%d", & a);
printf("Enter 2nd Num : ");
scanf("%d", & b);
printf("Enter Operator ( +, - , * , /) : ");
scanf("%c", & op);
if (op == '+') {
r = a + b;
printf("Ans = %f", r);
getche();
} else if (op == '-') {
r = a - b;
printf("Ans= %f", r);
}
//same as above for remaining 2 functions of * and /
else
printf("Error Occurred");
}
After typing the second number you press enter, right? %c in scanf accepts the first character it finds, so it returns the line break character corresponding to you pressing enter.
An easy fix is to add a space character before %c. It makes scanf skip any whitespace.
scanf(" %c",&op);
From the scanf documentation (http://www.cplusplus.com/reference/cstdio/scanf/):
Whitespace character:
The function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
Because %d ignore white-spaces and special characters. White-spaces and special characters are chars. So, %c has to take white-spaces and special characters as inputs.
You can test the output of the code below.
#include <stdio.h>
int main(void)
{
char p = 'w';
char l = 'x';
char t = 't';
printf("Give one, two or three chars: ");
scanf("%c%c%c", &p, &l, &t);
printf("p = %c, l = %c, t = %c \n", p, l, t); //
scanf("%c", &t);
printf("plt = %c%c%c \n", p,l,t);
return 0;
}

I have to press CTRL+D twice to end the input, why?how to correct?

I am supposed to write a program specified here:
Input
The input will consist of a series of pairs of integers a and b,separated by a space, one pair of integers per line. you should read the input until EOF.
Output
For each pair of input integers a and b you should output the sum of a and b in one line,and with one line of output for each line in input.
Sample Input
1 5
7 2
Sample Output
6
9
an I write this:
#include
main() {
int a, b;
int sum[100];
int i,j;
char c;
for(i=0; i<100; i++) sum[i]=0;
i=0;
do {
scanf("%d %d", &a, &b);
sum[i]=a+b;
i++;
} while((c=getchar())!=EOF);
for(j=0; j<i-1; j++) printf("%d\n", sum[j]);
}
what is strange for me is: why should I press CTRL+D(EOF) twice to end the input?Is there any better way to write this code?
Your first CTRL-D breaks the scanf. After that your program waits in getchar. If you check the output from scanf you have only one check.
#include <stdio.h>
main() {
int a, b;
int sum[100];
int i,j;
char c;
for(i=0; i<100; i++) sum[i]=0;
i=0;
while ( 2==scanf("%d %d", &a, &b))
{
sum[i]=a+b;
i++;
}
for(j=0; j<i-1; j++) printf("%d\n", sum[j]);
}
Your code shouldn't rely on EOF being hit by getchar(). Change this:
do {
scanf("%d %d", &a, &b);
...
} while((c=getchar())!=EOF);
to:
do {
if (scanf("%d %d", &a, &b) != 2)
break;
...
} while((c = getchar()) != EOF);
Alternatively you might omit getchar() call completely:
while (scanf("%d %d", &a, &b) == 2) {
...
}
When scanf() reads your line of input, it reads the two numbers, but it leaves the newline that terminates the line in the input stream. Then when getchar() reads the next character, it reads that newline. Since the newline is not EOF, it returns to the beginning of the loop.
Now scanf() runs again, and it sees the EOF that you typed after the newline. It returns without updating the variables. Then getchar() is called again, and you have to type another EOF for it to get it.

Resources