Unable scan character in while loop - c

i want infinite scan
this is my code:
int main() {
int i=1;
char score;
while(1)
{
printf("Please Input No %d of char",i);
scanf("%C",&score);
i++;
}
return 0;
}
my output:
Please Input No 1 of char:A
Please Input No 2 of char:B
Please Input No 3 of char:Please Input No 4 of char:C
Please Input No 5 of char:Please Input No 6 of char:
how do i fix my i variable in while loop normal.
thanks

Use getchar(); after scanf()
int main() {
int i=1;
char score;
while(1)
{
printf("Please Input No %d of char\n", i);
scanf("%c",&score);
getchar();
//or
scanf(" %c", &score);
// don't need getchar() here.
i++;
}
return 0;
}
Note that %C isn't standard.
And scanf("%c",&score); is taking a char but while We are pressing Enter this is an another input. So, we need getchar()

Related

Why does the number 10 get output in each iteration and how can I fix this?

I have a for loop, which I want to get the input from the user and print the associated ascii value. But it only asks for the user input in the second iteration, which is followed and preceded by the output 10. I tried to get rid of new-line characters, but it still prints out 10.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: \n");
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
Maybe simpler (though using scanf() for user input is not recommended)
scanf(" %c", &character);
// ^ skip otional leading whitespace
Your whole program using fgets() for user input (and my indentation, spacing, style; sorry)
#include <stdio.h> // printf(), fgets()
#include <stdlib.h> // strtol()
int main(void) {
int number;
char buffer[100]; // space enough
printf("Enter the number:");
fgets(buffer, sizeof buffer, stdin);
number = strtol(buffer, 0, 10); // error checking missing
for (; number > 0; number--) {
printf("Give a char: ");
fgets(buffer, sizeof buffer, stdin); // reuse buffer, error checking missing
if (buffer[0] != '\n') {
printf("The associated ascii value of '%c' is %i.\n", *buffer, *buffer);
}
}
return 0;
}
This should solve your problem. getchar() will read the extra newline character from buffer.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: ");
getchar();
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
regarding;
scanf("%c", &character);
the first time through the loop the '\n' is input.
on all following passes through the loop, the scanf() fails, so the value in character does not change.
This is a prime example of why your code should be error checking.
for instance, to error check the call to scanf():
if( scanf("%c", &character) != 1 )
{
fprintf( stderr, "scanf for a character failed\n" );
break;
}
the 1 is because the scanf() family of functions returns the number of successful: input format conversion specifiers or EOF and it is best to assure the 'positive' status.

Output printed twice instead of once [duplicate]

I tried to execute the following simple code in ubuntu 15.10 But the code behaves odd than expected
#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%c",&val);
int count=0;
for(i=0;i<20;i++){
if(a[i]==val){
printf("\n%c found at location %d",val,i);
count++;
}
}
printf("\nTotal occurance of %c is %d",val,count);
return 0;
}
output:
--------------------------
Enter the value : 12345678
Enter the value to be searched :
Total occurance of is 0
The second scanf to get the value to be searched seems not to be working. The rest of the code executes after the first scanf without getting input second time.
After first scanf(), in every scanf(), in formatting part, put a whitespace
So change this
scanf("%c",&val);
into this
scanf(" %c",&val);
Reason is, scanf() returns when it sees a newline, and when first scanf() runs, you type input and hit enter. scanf() consumes your input but not remaining newline, so, following scanf() consumes this remaining newline.
Putting a whitespace in formatting part makes that remaining newline consumed.
You can use fgets():
#include<stdio.h>
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
fgets(a, 20, stdin);
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
or clear stdin:
#include<stdio.h>
void clearstdin(void) {
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
clearstdin();
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
Also, see C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%d",&val); // here is different
i don't know why, but code above working...
scanf("%d",&val);
You can use " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

Infinite while loop not waiting for scaning data again in C

#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf(" %d", &i) > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
}
}
I want to continue the scan again if user entered a value other than integer when I run the above code with a char input it is running infinite loop. Please suggest why or any solution ...?
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf_s(" %d", &i) > 0) { // step-2
printf("Num=%d\n", i);
break;
}
else {
printf("Entered character.Pls enter int\n");
fseek(stdin, 0, SEEK_END);
}
}
}
If you enter a character say a for the above program it will not match with %d so it will remain in the buffer. The next time in the loop, it will again not match %d and you will enter an infinite loop.
What you can do, is read from the buffer until you encounter a newline character. The second loop will remove any characters until and including the newline character.
#include <stdio.h>
int main() {
int i;
char dummy;
while (1) {
printf("Enter no?\n"); // step -1
scanf(" %d", &i)
if (i > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
do{
scanf("%c",&dummy);
}while (dummy != '\n'); // Add this loop
}
}

replacing a character in string in C

Have to replace a user input character with another user input character and print the string . What am i doing wrong ?
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string");
gets(str);
//asking for replacement
printf("enter the character to be replaced");
scanf("%c",&a);
// which letter to replace the existing one
printf("enter the character to replace");
scanf("%c",&b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("the new string is");
puts(str);
}
scanf("%d",&a);
You get an integer ? not a character ? If it is a character, then you should use %c instead of %d
Add getchar() function between the two scanf().
Like
#include<stdio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string");
gets(str);
//asking for replacement
printf("enter the character to be replaced");
scanf("%c ",&a);
//Get the pending character.
getchar();
// which letter to replace the existing one
printf("enter the character to replace");
scanf("%c",&b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("the new string is");
puts(str);
}
The problem is when you give a character and pressed enter, newline will acts as one character and it will be get by the next scanf. To avoid that the getchar() is using.
Another Way:
Give space before the access specifier on character to replace,
Like
scanf(" %c",&b);
But before remove that getchar().
#include<stdio.h>
#include<conio.h>
int main() //main returns an int
{
int i;
char a,b,str[100];
printf("Enter the string\n");
fgets(str,sizeof(str),stdin);//gets is dangerous
printf("Enter the character to be replaced\n");
scanf(" %c",&a); //space before %c is not neccessary here
printf("Enter the character to replace\n");
scanf(" %c",&b); //space before %c is compulsory here
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
//else //This part is not neccessary
//continue;
}
printf("The new string is ");
puts(str);
return 0; //main returns an int
}
I've used fgets because gets is dangerous as it does not prevent buffer overflows.
The space before %c in the scanf is to skip blanks,i.e,spaces,new-lines etc and it isn't needed in the first scanf is that fgets also consumes the new-line characters and puts it into the buffer.
The reason that the else continue; isn't needed is that the loop is going to check the condition as it has reached the end of the loop body.
I've used int main() and return 0 because as per the latest standards,it should
Finally,you have an unused header conio.h in your program.
Try this, it worked for me:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string: ");
gets(str);
//asking for replacement
printf("enter the character to be replaced: ");
a = _getch();
printf("\n%c", a);
// which letter to replace the existing one
printf("\nenter the character to replace: ");
b = _getch();
printf("\n%c", b);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
else
continue;
}
printf("\nthe new string is: ");
puts(str);
}
You can remove the else block. It won't affect anything.

Why does this C loop skip the first attempt to input a letter?

This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.

Resources