Why is my for loop not taking 9 inputs? - c

My code only takes 5 values as input.? What am i doing wrong?
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[3][3];
int i,j,n;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%c",&arr[i][j]);
}
}
return 0;
}
How should i correct it?

Change
scanf("%c",&arr[i][j]);
to
scanf(" %c",&arr[i][j]);.
Notice the space given before specifier to consume \n left in stdin buffer when you pressed enter.
Each \n is working as input taking your space from input space.

It should work, but note that %c will read only a single character. Whitespace is not suppressed as it is for other (more "high-level") format specifiers, so if you're separating your characters by blanks of any kind those will be read instead of the actual characters.
Also note that you should check the return value of scanf(), it can fail if no suitable input is present.

The first input is stored in arr[0][0] then when you press enter(return key) it is stored in arr[0][1] and while you think you are inputting the second character actually you are giving the third input. Try the code below to see if you didnt get it.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[3][3];
int i,j,n;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Input array [%d][%d]",i,j);
scanf("%c",&arr[i][j]);
}
}
}
And as for the correction you need a scanf(" %c",&arr[i][j]); a space infront of %c to consume the \n
Hope it answers your question

Instead you can use gets(arr[i][j])
instead of scanf("%c",&arr[i][j]);
This will work perfectly. It is good idea to use gets() and puts() function instead of printf() and scanf() function for string and character in C

you can use fflush(stdin)
char arr[3][3];
int i,j,n;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%c",&arr[i][j]);
fflush(stdin);
}
}

Related

Trying to scanf but can't access a value it unless inputting another value

I am trying to dynamically initialize an array, but when I enter the while loop the first time printf prints the statement, but the next printf statement doesn't execute unless I put another value. I want to put values between
0--->n-1
First time printf statement executed but the 2nd time does not execute unless I enter any value. tried to enter 5 for the size, and put 0,1,2,3,4 for the values.
#include <stdio.h>
#include <malloc.h>
void main() {
Ex5();
system("pause");
}
void Ex5()
{
int size_a,n_res=0,res=0;
int *arr_a = input_array_dyn(&size_a);
res = includes(arr_a, size_a);
printf("res is %d ", res);
free(arr_a);
}
int* input_array_dyn(int *size) {
int i=0, *p_to_arr;
printf("enter size of arr:");
scanf_s("%d", size);
p_to_arr = (int*)calloc(*size,sizeof(int));
while(i<*size) {
printf("enter %d element", i);
scanf_s(" %d ", &p_to_arr[i]);
i++;
}
return p_to_arr;
}
The format string in
scanf_s(" %d ", &p_to_arr[i]);
is troublesome and could possibly be the cause of your problem.
The problem with the format string is the trailing space. The trailing space means that scanf_s will read all trailing space characters, until there are no more spaces. The problem is that for scanf_s to know there are no more spaces, you must enter some non-space input.
This leads to scanf_s blocking until you write a second input.
The solution is to not have any spaces in the format string at all:
scanf_s("%d", &p_to_arr[i]);
The leading space isn't needed either, as the "%d" specifier will skip leading space automatically.
If I understand you correctly, changing the format of the second scanf to "%d" should help. I've tested it locally and I'm able to enter all the values at once.

Simple C code not working

I have written a simple code to check whether a given character is present in the string entered by the user but it doesn't seem to work.
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],b;
int i,p=0,n;
printf("Enter the string-");
scanf("%s",a);
printf("\nEnter the character-");
scanf("%c",&b);
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
printf("\ncharacter is present in string\n");
p=1;
break;
}
}
if(p==0)
printf("\nchracter is not present in string\n");
return 0;
}
The output I get is this: http://i58.tinypic.com/2gvnedt.png
I do not see what is wrong with the code. If I replace "scanf("%s",a);" with "gets(a);" it works fine. Why?
Help is appreciated. Thanks!
Add a space character in:
scanf(" %c",&b);
^
To consume the trailing \n character that is left in stdin after the first scanf.
So a \n is left in the standard input from which scanf is reading. So when a new scanf is met it scans the old \n character.
To neutralize that effect I put a space character in scanf i.e. I am telling it to expect to read a \n or space or \t and then to read a %c.

Why 2nd scanf doesn't work in my program?

scanf("%d %c",&size,&chara); works but separate scanf for character input does not work. I show these inside the code. Why is that?
void squareCustomFill(int size, char chara);
int main(void) {
int size,i,k;
char chara;
printf("Enter size of square: "); //This works
scanf("%d %c",&size,&chara);
//printf("Enter fill character: "); BUT WHY DOES NOT THIS WORK??
//scanf("%c",&chara);
squareCustomFill(size,chara);
return 0;
}
void squareCustomFill(int size, char chara){
int i,k;
for (k=1;k<=size;k++){
for(i=1;i<=size;i++)
printf("%c",chara);
printf("\n");
}
}
Scanf did not consume the \n character that stayed in the buffer from the first scanf call.
So the second scanf call did.
You have to clear the stdin before reading again or just get rid of the newline.
The second call should be
scanf(" %c",&chara);
^ this space this will read whitespace charaters( what newline also is) until it finds a single char
Yes I believe Armin is correct. scanf will read in whitespace (spacebar, newline, etc.). When you're inputting values if you click the space bar or enter right after the first scanf, the second scanf will read in that value (space, newline, etc.). So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. If you want them separate just do what Armin suggested: scanf(" %c",&chara).
Throw a getchar() in between them and slurp up that extraneous newline.

Reading multiple lines of input with scanf

Writing a program for class, restricted to only scanf method. Program receives can receive any number of lines as input. Trouble with receiving input of multiple lines with scanf.
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]",s)==1){
printf("%s",s);
}
return 0;
}
Example input:
Here is a line.
Here is another line.
This is the current output:
Here is a line.
I want my output to be identical to my input. Using scanf.
I think what you want is something like this (if you're really limited only to scanf):
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]%*c",s)==1){
printf("%s\n",s);
}
return 0;
}
The %*c is basically going to suppress the last character of input.
From man scanf
An optional '*' assignment-suppression character:
scanf() reads input as directed by the conversion specification,
but discards the input. No corresponding pointer argument is
required, and this specification is not included in the count of
successful assignments returned by scanf().
[ Edit: removed misleading answer as per Chris Dodd's bashing :) ]
try this code and use tab key as delimeter
#include <stdio.h>
int main(){
char s[100];
scanf("%[^\t]",s);
printf("%s",s);
return 0;
}
I'll give you a hint.
You need to repeat the scanf operation until an "EOF" condition is reached.
The way that's usually done is with the
while (!feof(stdin)) {
}
construct.
Try this piece of code..
It works as desired on a GCC compiler with C99 standards..
#include<stdio.h>
int main()
{
int s[100];
printf("Enter multiple line strings\n");
scanf("%[^\r]s",s);
printf("Enterd String is\n");
printf("%s\n",s);
return 0;
}

Problem while scanning a char and float simultaneously

I am trying to take five character and 5 float input.
main()
{
char c[5];
float q[5];
int i;
for(i=0;i<5;i++)
{
printf("\n%d ",i);
scanf("%c",c+i);
scanf("%f",q+i);
}
}
But the output is absurd. After two sequential scans, it skips third scan and then again skips fifth scan.
I am not able to understand why is it showing such a behaviour.
I am working on gcc compiler.
Use of scanf is not recommended because of problems like this.
Instead use fgets to read the entire line and then use sscanf to extract what you want(a char or a float) from the line just read:
char line[MAX];
for(i=0;i<5;i++)
{
if( fgets(line,MAX,stdin) && sscanf(line,"%c", c+i)!=1 )
*(c+i) = 0;
if( fgets(line,MAX,stdin) && sscanf(line,"%f", q+i)!=1 )
*(q+i) = 0.0;
printf("%c %f\n",*(c+i),*(q+i));
}
To directly answer why the 3rd and every other scan "skips", it is the way scanf() and the %c format works. When there is a call to scanf(), you typically have to press enter to "submit" the input. Consequently that inserts a newline character into the stdin stream.
When the previous float scan got inputted, the newline is still left in the stream. When the character scan gets reached, that remaining newline character is read in since it fits effectively "skipping" the call.
You should use fgets() with sscanf() as codaddict suggests.
But as a quick fix, you could try adding a call to getchar() after the float scan to consume that newline character from the stream.
edit:
You're saying this doesn't work? (assuming you input the correct kinds of values, one per scanf call)
main()
{
char c[5];
float q[5];
int i;
for(i=0;i<5;i++)
{
printf("\n%d ",i);
scanf("%c",c+i);
scanf("%f",q+i);
getchar();
}
}
You should try this:
int main(){
char c[6];//char array size must be 6 to store five charecter
//as null-terminator('\0')will use the last one
float q[5];
int i;
for(i=0;i<5;i++){
printf("\n%d\n",i);fflush(stdout);
scanf("%c",&c[i]);fflush(stdin);//fflush(stdin) to clear input stream that
//next scanf() won't skip
scanf("%f",&q[i]);fflush(stdin);//fflush(stdin) to clear input stream that
//scanf() won't skip at new loop
}
return 0;
}
fflush() is not defined on an input stream, like stdin. Don't do it.
If you want to "read and discard until newline", then do:
int ch;
do {
ch = getchar();
} while (ch != EOF && ch != '\n');
Note that %c means "read the next character in the input stream, even if it's whitespace, then stop". %f means "read and discard whitespace, then try to read a float from the input stream, then stop."
Your code should be like this :
main()
{
char c[5];
float q[5];
int i;
for(i=0;i<5;i++)
{
printf("\n%d ",i);
scanf("%c",c+i);
while (getchar()!='\n');
scanf("%f",q+i);
while (getchar()!='\n');
}
}
the sentence while (getchar()!='\n'); search till the end of input, so it would not take '\n' as an input value for q+i.Also another while (getchar()!='\n'); after scanf q+i,since you use loop.
Problem in scanning a char value after a float value.
Solution is very simple!!!
instead of writting your code like this
scanf("%c",&...)
try this,
scanf(" %c",&...)
A Space before the"%c" will resolve the problem by neglecting the value of the Return(Enter) key when pressed after typing the value of the float as an input.
When a float value is scanned before a character value.
The value obtained by pressing the Return(Enter) key is collected in the following char variable. Using a space before(" %c",&...) discards the value collected of the Return(Enter) Key, Causing the Char value to be scanned in the next line. Thus solving The Scanning Float-Char problem.

Resources