Why scanf or fgetc does not work as expected - c

Following is my code and it is not stopping for first index and I wonder why ? Same is the result with scanf
#include<stdio.h>
void main()
{
int n = 0, i = 0;
char arr[10];
printf("How many characters do u want to enter ");
scanf("%d", &n);
//printf("\n\t%d", n);
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin);
arr[i] = ch;
//putchar(arr[i]);
}
i = 0;
printf("You have entered characters are \n");
for(i = 0; i < n; i++)
{
printf("arr[%d] = %c\n", i, arr[i]);
}
printf("\n");
}
When I run this code I get following
How many characters do u want to enter 5
Enter 0 character-->
Enter 1 character-->
program does not wait for first character to input.

There is an endline character on the input stream that is left there by scanf("%d",&n) and is read by the first fgetc
Same is the result with scanf
Are you using scanf correctly? Try the following (don't miss the space before the %c):
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
scanf(" %c", &arr[i]);
}

Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.
So, when fgetc starts reading from STDIN, it reads a character and leaves the newline character. So you should either use scanf() i.e. scanf(" %c", &arr[i]); as suggested by Cubbi. Or you need to discard that newline character otherwise. You may use this
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin); // newline is consumed here
if(ch=='\n')
ch = fgetc(stdin); // you get the expected value
arr[i] = ch;
//putchar(arr[i]);
}

Related

program stops working if i use a value used by user

#include<stdio.h>
//prints a shape using users input
int main() {
int i, j ;
char a ;
i = 0 , j= 0;`
printf("enter your charecter :");
scanf("%s", &a);
for ( j = 0; j < 5; j++) {
for ( i = 0; i < 5; i++) {
printf("%s", a);
}
printf("\n");
}
return 0;
}
program stops after input by user
&a does not refer to a string. %s will write all characters entered and nul terminate so will overrun the the single character to which &a refers.
You have the same format specifier mismatch for the output. The format specifier for a single character is %c, however in this case you could use getchar() / putchar().

How can I take input character in a character array using %c and produce the right output using %s?

This is my code.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
char ch[100];
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf(" %c", &ch[i]);
}
printf("%s\n", strupr(ch));
return 0;
}
At first, I want to take the size of the character array in n variable. After, i want to take n character's and assign the array. The output comes from this program is right but it also produce some garbage values.
For example:
5
s d g h f
Output: SDGHFC└U▄■`
How can i ignore the garbage values from my output?
Simply initialize your array ch[] to all zeros. I.E.
for (i = 0; i < 100; i += 1) { ch[i] = '\0'; }
Put this line just after the declaration of ch[].
As you are reading character the spaces you are providing in your input, will also be considered as characters, and strupr(c) will give some shaggy output, also you have to manually provided null character at the end of your character array. Below program might help you find your answer
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
for(i = 0; i < n; i++){
char temp;
scanf("%c", &temp);
if(temp != '\n')
ch[i] = temp;
else
break;
}
ch[n] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Your Input should look like
5
sdghf
To give input with spaces. Program will look like.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
char temp;
i = 0;
while(scanf("%c", &temp)){
if(temp == ' ')
continue;
if(temp != '\n')
ch[i++] = temp;
else
break;
}
ch[i] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Now, you can give your character in any arrangement as you want.

Searching a char value inside char array in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am studying the c language in our class I create some code to find a some number inside other array but when I try it with char value my code is not working in same as working with int value.
This is my code:
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
//printf("%d\t", (i+1));
//if ( i + 1 == num ) {
// scanf("%c", &a[i]);
//} else {
scanf("%c", &a[i]);
//}
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf("%c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
I try to fixed many time but each time I get error, so the above one is working but it scape the some input value during input.
Thank you WhozCraig, user3121023 for your advices, the whitespace in scanf(" %c", &a[i]); and scanf(" %c", &ele); make some unwanted inputs so this is a my code and its working like charm. :))
I just add space before the %c and every thing is okay.
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
printf("%d\t", (i+1));
scanf(" %c", &a[i]);
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf(" %c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
There is a problem in your program that causes surprising behavior:
scanf("%d", &num) reads a number from standard input but leaves the newline typed by the user pending as the next character to be read.
Further calls to scanf("%c", &a[i]); read this pending newline and num-1 more characters from the user, leaving the rest of his input pending...
The final scanf("%c", &ele); reads whatever byte is pending in stdin, either a character from the user or the pending newline.
Hence the program behaves as if it does not execute the last scanf().
You should read input from the user one line at a time with fgets() or flush the pending newline with a loop:
#include <stdio.h>
int main() {
int num, i, c;
char a[99], ele;
printf("Enter the number of character:");
// get the length of array by the num value
if (scanf("%d", &num) != 1 || num < 0 || num > 99)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the characters on a single line: \n");
// a loop for getting values for our a[array]
for (i = 0; i < num; i++) {
if (scanf("%c", &a[i]) != 1)
return 1;
}
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the character to be searched: ");
// get the value for ele, to use ele for searching inside our a[array]
if (scanf("%c", &ele) != 1)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
// use a for loop
for (i = 0; i < num && ele != a[i]; i++) {
i++;
}
if (i < num) {
printf("Character %c found at the offset %d\n\n\n", ele, i);
} else {
printf("Character %c Not Found!\n\n\n", ele);
}
return 0;
}

Why is this reverse string program not working?

I am new to C programming so please do forgive my naivety. The following program when outputted fails to print the last character of the input string as the first character of the output string.
For example:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
Why is the o not printing?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
There is a side effect you take care of:
After scanf("%d", &n);, there is a pending newline in the input stream buffer.
When you later input n characters, scanf("%c", &string[i]) first reads the pending newline, then the n-1 first characters you type and the remainder of your input stays in the input buffer.
scanf() is a very clunky function. It is difficult to use properly.
Here is a way to fix your problem:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Your scanf() should start with a space( more info about that ). Here is the code:
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf(" %d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &string[i]);
}
/* Just to be safer. */
string[n] = '\0';
printf("The reversed string is: ");
for (int i = (n-1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Adding the space to the format string enables scanf to consume the
newline character from the input that happens everytime you press
return. Without the space, string[i] will receive the
char '\n'
So, merely one space is put before format specifier %c at line 11.
scanf(" %c", &string[i]);

Switching letters in a string in C

I'm not sure why this code does not work.
This code is supposed to, for example, switch all a's in the string to b's, and all b's to a's and print the result.
input:
abcd
a b
c d
Intended output:
badc
Code:
int main()
{
int n, m, i, j;
scanf("%d %d", &n, &m);
char s[n+1], x[m+1], y[m+1];
scanf("%s", s);
for(i=0; i<m; i++)
{
scanf("%c", &x[i]);
scanf("%c", &y[i]);
}
for(j = 0; j < m; j++)
{
for(i = 0; i<n; i++)
{
if(s[i] == x[j])
s[i] = y[j];
else if(s[i] == y[j])
s[i] = x[j];
}
}
printf("%s", s);
return 0;
}
As I commented you need a space before the %c in these lines
scanf("%c", &x[i]);
scanf("%c", &y[i]);
to prevent the %c format type reading the white-space left in the input buffer by previous scanf calls. Change to
scanf(" %c", &x[i]);
scanf(" %c", &y[i]);
Your logic is correct. You just need to put a space before %c specifier in both of the scanf
for(i=0; i<m; i++)
{
scanf(" %c", &x[i]);
scanf(" %c", &y[i]);
}
and it will work. This is because the \n leftover by the previous scanf is read by second scanf and same is happening for the space in between the the input characters a b and c d. A space before %c in scanf will consume all white-spaces.
You can change loop to replace characters in only one iteration
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(s[i] == x[j])
{
s[i] = y[j];
break;
}
if(s[i] == y[j])
{
s[i] = x[j];
break;
}
}
}
In addition to https://stackoverflow.com/a/33397902/2410359
Code does not insure that s is null character terminated at print time - leads to undefined behavior. Should use for(i = 0; s[i] && i<n; i++) to prevent overwriting it.
This may account for excessive time usage.
OP posts below as input. Certainly 2 numbers must precede that for scanf("%d %d", &n, &m);
abcd
a b
c d

Resources