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.
Related
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.
When I have a scanf followed by a getchar, why does the getchar always keep getting the last delimiting character of scanf? How can I stop that? I tried looking into "format specifiers" for scanf, read quite a few things but none solves this.
The code is shown below -
#include <stdio.h>
#include <conio.h>
int main()
{
int a;
char b;
printf ("Enter an integer \n");
scanf_s(" %d", &a);
printf("Enter a character \n");
b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
return 0;
}
The output is as below -
Enter an integer
4563
Enter a character
The integer you entered is 4563
The character you entered is
The enter key I press at the end of integer entry is being returned by getchar. The screen does not even stop after printing "Enter a character". What is the correct way to do this ?
Use the scanf(" %c", &b) instead of getchar()
When you put the space befor the %c you clean the buffer
Or you can clean the buffer using this too:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
Complete example:
int main(void)
{
printf("Enter an integer \n");
int a;
scanf(" %d", &a);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
}
printf("Enter a character \n");
char b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
}
But I think the scanf()
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.
#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);
...
}
I am trying to convert the character of which a user types in to its character code.
int main(){
char converter;
scanf("enter a character: %c", &converter);
printf("your character code is %d", converter);
return 0;
}
This will give you the key code for each character:
#include <stdio.h>
main()
{
char converter;
printf("enter a character: ");
scanf("%c", &converter);
printf("your character code is %d", (int)converter);
return 0;
}
Also, each corresponding code can be found here:
http://www.expandinghead.net/keycode.html