#include<stdio.h>
int main() {
char *str, ch;
int count = 0, i;
printf("\nEnter a string : ");
scanf("%s", str);
printf("\nEnter the character to be searched : ");
scanf("%c", &ch);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ch)
count++;
}
if (count == 0)
printf("\nCharacter '%c'is not present", ch);
else
printf("\nOccurence of character '%c' : %d", ch, count);
return (0);
}
while i executing this code the string is taken after that it will not taking any characters and showing results.
Your code might crash (happened to me when verifying it on my machine) because you did not allocate space for str...
you should change char *str, ch; to something like char *str = malloc(100), ch;
Also, change scanf("%c", &ch); to scanf(" %c", &ch); to resolve your problem. This happens because when you enter your string, you end it with enter, and that enter is consumed by your next scanf(%c) and so, your second scanf() only reads the enter instead of reading the char you intend. scanf(" %c", &ch); will ignore all whitespaces, including the previously entered enter :-) and wil allow your char to be processed
Always write scanf like this, to read the previous newline character:
printf("\nEnter the character to be searched : ");
scanf(" %c", &ch);
OR
use getchar()
printf("\nEnter the character to be searched : ");
getchar();
scanf("%c", &ch);
Defining a max length would be the simplest way to solve this. Insted of using scanf, I would recomend using fgets as done below. It is much more failsafe since you can define the max number of characters to be read.
Tutorialspoint's explanation of fgets
#define MAX_LENGTH 100
int main() {
char str[MAX_LENGTH], ch;
int count = 0;
printf("\nEnter a string : ");
fgets(str, MAX_LENGTH, stdin);
printf("\nEnter the character to be searched : ");
scanf("%c", &ch);
...
}
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
MY CODE:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf("%c",&g2);
printf("\nEnter the grade of student 3: ");
scanf("%c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
OUTPUT:
Enter the grade of student 1: A
Enter the grade of student 2:
Enter the grade of student 3:
//I am getting a line break and couldn't enter the value of student 2 and the cursor moves to student 3!!
Try doing:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf(" %c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
Sorry, I'm new to this.
Just give a space before %c in scanf to get desired input. The below is your own code where I've added space in the second and third scanf statements.
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
And well, the reason? If you don't, then the next scanf statement assumes the new line you create by pressing "Enter" as a new character, which is \n. So we add a space in scanf to let the statement know that space is not considered an input.
It is often easier to always read an entire line, like this:
#include <stdio.h>
void ReadLine(char result[], int resultLen)
{
int ch, i;
i = 0;
ch = getchar();
while ((ch != '\n') && (ch != EOF)) {
if (i < resultLen - 1) {
result[i] = ch;
i++;
}
ch = getchar();
}
result[i] = '\0';
}
int main(void)
{
char g1[2], g2[2] ,g3[2];
printf("Enter the grade of student 1: ");
ReadLine(g1, sizeof g1);
printf("Enter the grade of student 2: ");
ReadLine(g2, sizeof g2);
printf("Enter the grade of student 3: ");
ReadLine(g3, sizeof g3);
printf("%s%s%s\n", g1, g2, g3);
return 0;
}
first Scanf will not read/flush the "\n" after reading the single char.
this character on input buffer will make the 2nd and 3rd scanf to get execute and fail without actually prompting the user.
There are multiple ways to handle this.
read complete line
use gets/fgets to rad complete inputline
then use scanf to read from buffer
eg:
fgets(buff, 255, stdin);
sscanf(buff, "%c", &value);
execute a char read after every scanf statement.
getch()
Put a preceeding " " in front of every "%c" used in scanf.
this will skip the special char.
"scanf(" %c", &value);"
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.
For some reason my C program closes immediately after outputting "Enter a letter (D/E/F): "
I would like to be able to store 3 characters in the letters[] array so that I can print them later on.
I use Visual Studio 2017 and the program has no errors. It just seems to skips everything after printf("Enter a letter (D/E/F): ");.
I think the problem has to do with scanf_s, but I don't exactly know what the problem is or how to fix it. Here's my program:
#include <stdio.h>
int main(void)
{
char letters[3];
char ch;
printf("Enter a letter (A/B/C): ");
scanf_s(" %c", &ch);
letters[0] = ch;
printf("Enter a letter (D/E/F): ");
scanf_s(" %c", &ch);
letters[1] = ch;
printf("Enter a letter (G/H/I): ");
scanf_s(" %c", &ch);
letters[2] = ch;
printf("You entered %c, %c, and %c.", letters[0], letters[1], letters[2]);
getchar(); getchar(); // PAUSE
return 0;
}
Please help.
Changed scanf_s(" %c", &ch); to scanf_s(" %c", &ch, 1); and the program now works!
Thanks Weather Vane, Some programmer dude, Kal Karaman, Weather Vane again, and this webpage: http://faculty.edcc.edu/paul.bladek/CS131/scanf_s.htm!
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.
I am not too familiar with C syntax. I need to process some data based on user input. Although I processed the data successfully but I am stuck at user input section. I removed the unnecessary data processing section and made a simple example of how I am taking the user input. Can anyone tell me what's the problem with below code :
int i, number;
char *str;
str=(char*)malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
scanf ("%[^\n]%*c", str);
printf("%s", str);
}
Output:
"Enter count : " appears fine, but whenever I provide some value and hit enter it's showing me only 'count' number of Enter string: without enabling user to enter the string.
For example -
Enter count : 2
Enter string:
Enter string:
But if I discard the count input section and provide any fixed value, like
for(i=0; i<5; i++)
it works fine
Thanks in advance
FYI, there is no issue in for(i=0; i<number; i++), problem is in scanning logic.
Actually, scanf ("%[^\n]%*c", str); is not right. you should use %s to read strings, not %c, which reads a single character, including the ENTER (newline).
Rather, i would suggest, use fgets() for inputs. It's a whole lot better in every way. Check the man page here.
Maybe you can use something like
//Dummy code
int i, number;
char *str;
printf("Enter count : ");
scanf("%d", &number);
str=malloc(number*sizeof(char)); //yes, casting not required
fgets(str, (number-1), stdin ); //"number" is used in different context
fputs(str, stdout);
EDIT:
Working code
#include <stdio.h>
#include <stdlib.h>
#define SIZ 1024
int main()
{
int i, number;
char * str = malloc(SIZ * sizeof (char));
printf("Enter the number :\n");
scanf("%d", &number);
getc(stdin); //to eat up the `\n` stored in stdin buffer
for (i = 0; i < number; i++)
{
printf("Enter the string %d :", (i+1));
fgets(str, SIZ-1, stdin);
printf("You have entered :");
fputs(str, stdout);
}
return 0;
}
scanf("%s",str); Use this instead of the code you are using to take string inputs in a character array.
There is a newline character \n after entering count value which is picked up by %c in your scanf()
Just use %s to scan strings as shown below.
scanf("%s",str);
If there are spaces in your input.
Then do
char c[50];
fgets(c,sizeof(c),stdin);
Check the below code:
#include <stdio.h>
#include<stdlib.h>
int main(){
int i, number;
char *str;
str=malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d%*c", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
fgets(str,1000,stdin);
printf("%s", str);
}
}