scanf() function for single char not working - c

I am trying to write a simple function replaceChar in C to replace the single char A which was initialized as 0 in main. When main calls replaceChar, it prints input as 'b', but after the function, it prints A as nothing.
I don't understand why the character input isn't being saved to A. I have tried initializing A as '/0' and " " as well. Is it something to do with pointers?
#include <stdio.h>
void replaceChar(char input);
int main () {
char A = 0;
replaceChar(A);
printf("2: %c\n", A);
return 0;
}
void replaceChar(char input) {
printf("Enter a single character: ");
scanf(" %c", &input);
printf("1: %c\n", input);
}
returns:
Enter a single character: b
1: b
2:

You're passing input by value, so when you write into it you're just writing in the copy, not in the original. You want something like this:
#include <stdio.h>
void replaceChar(char input);
int main () {
char A = 0;
replaceChar(&A);
printf("2: %c\n", A);
return 0;
}
void replaceChar(char *input) {
printf("Enter a single character: ");
scanf(" %c", input);
printf("1: %c\n", *input);
}

Related

First %s scanf value get ignore but second %s can store the value

int main()
{
char i;
char s;
printf("Enter first char : ");
scanf("%s", &i);
printf("Enter second char : ");
scanf("%s", &s);
printf("%c", i);
printf("%c", s);
}
The output turn out only print second scanf value while the first scanf value does not print out.
int main()
{
char i;
char s;
printf("Enter first char : ");
scanf("%c", &i);
printf("Enter second char : ");
scanf(" %c", &s);
printf("%c", i);
printf("%c", s);
}
When change to use %c both scanf value can be print out.
Why does the %s only store the last input while the first get ignored?
%s is to scan string :
scanf(" %s",&string);
Or
scanf("%s[^\n]",string);
%c to scan only one caracter :
scanf(" %c",&caracter);
in your first code ,if you want to read two string and print them :use this code
#include <stdio.h>
int main()
{
char i[150];
char s[150];
printf("Enter first char : ");
scanf("%s[^\n]",i);//scan the first string
printf("Enter second char : ");
scanf("%s[^\n]",s);//scan the second string
printf("%s", i);
printf("\n");
printf("%s", s);
printf("\n");
printf("%c",i[1]);//if you want to print the second caracter in the string i
printf("\n");
printf("%c",s[0]);//if you want to print the first caracter in the string s
}

Taking a string input using gets() function in C [duplicate]

I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.
scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}
The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}

Why does the following c code not work?

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

C language - strcmp returns 0 always and strcpy not copying the string in another array

I want to run this code where I enter two strings and user put the option for performing the following task.
After I enter 'a' in the menu, the statement strcpy(s_1,s_2); the string is copied to s_1 but when I added
#include <string.h>
it asked me to use strcpy_s() which I did and code stopped working.
When I enter 'b' in the menu, I get only one output
Both Strings are equal to each other
I don't understand why strcmp() returns 0 always.
It would be great if someone help me out in this issue.
By the way I'm using Visual Studio 2015 for compiling my C code.
#include< stdio.h>
#include< string.h>
#include< stdlib.h>
#include< process.h>
//USER-DEFINED FUNCTIONS
char top_down();
char copy_function();
char compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header()
{
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
main()
{
//VARIABLE DECLARATION
char x =
{ 0 };
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
//TERMINAL-PAUSE
system("pause");
}
char top_down()
{
char s1[MAX] =
{ 0 }, s2[MAX] =
{ 0 }, x =
{ 0 };
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf_s("%c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x)
{
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s1);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
return;
}
}
char copy_function(char s_1[], char s_2[])
{
int x = 0;
x = strlen(s_2);
printf("Second String will be copied to First string now \n");
//strcpy(s_1, s_2);
strcpy_s(s_1, x, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
return;
}
char compare_function(char s_1[], char s_2[])
{
int a = 0, l1 = 0, l2 = 0, i = 0;
printf("First String will be compared to Second String now \n ");
//printf("\n");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
return;
}
Not sure if your program is in progress. I modified it and removed anything I thought was not necessary.
The functions' signatures change to void
Removed x in main
Return type of main set to int (It is int by default, but this spares you the warning of the compiler)
I work on Linux, so I removed the system(...), feel free to add it.
Only left variables declarations in top_down (not important, but an initial value should have a meaning and in your case there is no meaning to 0)
Changed scanf_s("%c", &x); to scanf(" %c", &x); (note the space. not sure if on windows that makes a difference. please check.)
Changed the function call compare_function(s1, s1); to compare_function(s1, s2);
Removed the return statements in the void functions
In copy_function I removed int x = 0; and x = strlen(s_2);
In copy_function I changed strcpy_s(s_1, x, s_2); to strcpy(s_1, s_2);
In compare_function I removed int a = 0, l1 = 0, l2 = 0, i = 0;
You use label/goto. That's ok, but considered not cool nowadays. You could use a loop and break in case of an invalid option.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//USER-DEFINED FUNCTIONS
void top_down();
void copy_function();
void compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header() {
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
int main() {
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
return 0;
}
void top_down() {
char s1[MAX], s2[MAX], x;
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf(" %c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x) {
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s2);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
}
}
void copy_function(char s_1[], char s_2[]) {
printf("Second String will be copied to First string now \n");
strcpy(s_1, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
}
void compare_function(char s_1[], char s_2[]) {
printf("First String will be compared to Second String now \n ");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
}

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.

Resources