#include<>
int calc(int,int,char);
void main()
{
int a,b;
char c;
printf("enter 2 nos");
scanf("%d%d",&a,&b);
printf("enter op");
scanf("%s",&c);
printf("the ans is %d\n",calc(a,b,c));
}
int calc(int a,int b,char c)
{
int ans;
switch(c)
{
case'+':ans=a+b;break;
case'-':ans=a-b;break;
}
return ans;
}
why does this program give the output as b...it works when i give a, b and c as global variables...what change should i do if i want them as local variables...using functions
scanf("%s",&c); causes undefined behavior. You are storing at least two characters ['+', '\0'] and you have only allocated space for one.
You might consider scanf(" %c", &c);. Note that I intentionally added a space in the format string to eat any whitespace that the user might include.
char c;
...
scanf("%s",&c);
Is plain wrong, even if c is a global variable.
Your scanf will take input from the keyboard and store the string you type at the address given as second parameter (in your case the address of c). But c has only space for a single character, and your string inputted with scan will take at least 2 characters (the one you type and th terminating zero).
In your case you get undefined behaviour, which means that your program may
appear to work
crash each time you run it
appear to work with a certain string you type, and crash with another
or any other odd behaviour
You need this:
char c[10];
...
scanf("%9s",c);
...
printf("the ans is %d\n",calc(a,b,c[0]));
which lets allows you to input a string of length 9 (9 characters + terminating zero = 10).
Related
I created a struct datatype 'ans' that contains three string datatype member variables a[2],b[2],c[2]. Inside main, I created a struct variable 'p' to accept the three string inputs and then pass it to a function - void f1(ans *x) via call by reference to print the strings. Now in the function, instead of printing the three separate strings (*x).a,(*x).b,(*x).c, it is printing the whole string joined together. I am attaching the code and output for reference:
#include <stdio.h>
typedef struct
{
char a[2];
char b[2];
char c[2];
} ans;
void f1(ans *x) {
printf("The strings are :\n");
printf("%s\n",(*x).a);
printf("%s\n",(*x).b);
printf("%s\n",(*x).c);
}
int main() {
ans p;
printf("Enter for a:\n");
scanf("%s", p.a);
printf("Enter for b:\n");
scanf("%s", p.b);
printf("Enter for c:\n");
scanf("%s", p.c);
f1(&p);
return 0;
}
Sample output:
Enter for a:
ab
Enter for b:
cd
Enter for c:
ef
The strings are :
abcdef
cdef
ef
Can anyone explain why is this showing as output instead of the following:
The strings are:
ab
cd
ef
I can't figure out what's happening :(
In scanf("%s", p.a);, scanf reads characters and writes them to the memory pointed to by p.a. It also writes a terminating null character after them. Since the a member of the structure is declared as char a[2];, when scanf writes more than two characters, including the terminating null, the behavior is not defined by the C standard.
In printf("%s\n",(*x).a);, for %s, printf takes a pointer to a char and prints the characters it finds there until a terminating null character marks the end of the string. When there is no terminating null character the array that is (*x).a, printf overruns the array, and the behavior is not defined by the C standard.
To fix the problem, ensure there is enough space in the arrays for all the characters to be written into them, including the terminating null character, or ensure that no more characters are written in the arrays than will fit.
if you enter "ab", scanf will scan string as "ab\0" which is 3 characters, therefore your a[2] won't fit as same as other variabls.
To prevent scanf from overruns the array, a simple adaptation of your program, from the several that can be suggested:
#define MAXCH 3
typedef struct
{
char a[MAXCH];
char b[MAXCH];
char c[MAXCH];
} ans;
void f1(ans *x)
{
printf("The strings are :\n");
printf("%s\n",(*x).a);
printf("%s\n",(*x).b);
printf("%s\n",(*x).c);
}
int main()
{
ans p;
char in[128];
printf("Enter for a:\n");
scanf("%s",in);
snprintf(p.a,MAXCH,"%s",in);
printf("Enter for b:\n");
scanf("%s",in);
snprintf(p.b,MAXCH,"%s",in);
printf("Enter for c:\n");
scanf("%s",in);
snprintf(p.c,MAXCH,"%s",in);
f1(&p);
return 0;
}
Sample output:
Enter for a:
abcdefgh
Enter for b:
cdefghij
Enter for c:
efghijkl
The strings are :
ab
cd
ef
When you declare two variables char a,b; and then you use first 'a' and then 'b',it prints only b, but if you declare it 'b' then 'a', it has no problem printing both in ASCII,the point of the program is to read 121 and 120 and to print yx. the problem - https://prnt.sc/pr5nww
and if you swap them -https://prnt.sc/pr5mt5
#include <stdio.h>
#include <stdlib.h>
int main(){
char a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("%c",a);
printf("%c",b);
}
This is kind of a confusing situation. When it comes to mixing char and int values (as you might do when investigating the numeric values of characters in a character set), it turns out the rules for scanf and printf are almost completely different.
First let's look at the scanf lines:
char a,b;
scanf("%d",&a);
scanf("%d",&b);
This is, in a word, wrong. The %d format in scanf is for scanning int values only. You cannot use %d to input a value of type char. If you want to input a character, the format for that is %c (although it'll input it as a character, not a number).
So you'd need to change this to
char a,b;
scanf("%c",&a);
scanf("%c",&b);
Now you can type characters like A and $ and 3 and have them read into your char variables a and b. (Actually, you're going to have additional problems if you hit the Return key between typing the characters for a and b, but that's a different story.)
When it comes to printing the characters out, you have a little more freedom. Your lines
printf("%c",a);
printf("%c",b);
are fine. And if you wanted to see the integer character-set values associated with the characters, you could have typed
printf("%d",a);
printf("%d",b);
and that would have worked, too. This is because when you call printf (and other functions ike it), there are some automatic conversions that take place: types char and short int are automatically promoted to (passed as) int, and type float is promoted to double. But these automatic conversions happen only for values of those types (as when calling printf). There a=is no such conversion when you're passing pointers to these types, as when calling scanf.
What if you wanted to read numbers, not characters? That is, what if you wanted to input the number 65 and see it get printed as capital A? There are several possible ways to do that.
The first way would be to continue to use %d in your scanf call, but change the type of your variables to int:
int a,b;
scanf("%d",&a);
scanf("%d",&b);
Now you can print a and b out using either %c or %d, and it'll work fine.
You could also use a temporary int variable, before reassigning to char, like this:
char a,b;
int tmp
scanf("%d",&tmp);
a = tmp;
scanf("%d",&tmp);
b = tmp;
The final, lesser-known and somewhat more obscure way, is to use the h modifier. If you say
char a,b;
scanf("%hhd",&a);
scanf("%hhd",&b);
now you're telling scanf, "I want to read decimal digits, but the target variable is a char, not an int."
And, again, you can print a and b out using either %c or %d, and it'll work fine.
the point of the program is to read 121 and 120 and to print yx
Do
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char a, b;
/* Scan into the half of the half of an int (the leading blank
makes scanf() eat whitespaces): */
scanf(" %hhd", &a);
scanf(" %hhd", &b);
/* Print the half of the half of an int: */
printf("%hhd", a);
printf("%hhd", b);
}
To print the characters literally do the printing part like this:
...
printf("%c", a);
printf("%c", b);
}
I am using Ubuntu 14.04 and gcc 4.8.4
#include<stdio.h>
void main()
{
char c[15];
printf("enter a character\n");
scanf("%15c",c);
printf("%s\n",c);
}
Output:
enter a character
qwertyuiopasdfghjkl
qwertyuiopasdfg
When I execute the program above with more than 15 characters as input, the output does not return garbage values. But when I execute the program below:
#include<stdio.h>
void main()
{
char c[5];
printf("enter a character\n");
scanf("%5c",c);
printf("%s\n",c);
}
I am giving input which is more than 5 characters. It returns output with garbage values.
The %c directive is for reading individual characters and character arrays, but not for those arrays specifically used as C strings. In particular, it does not store a null character after the last character transferred from the input.
Therefore, both of your scanf() calls are perfectly fine, but the subsequent printf() calls are not. In each case, the contents of the array designated by c are not null-terminated, therefore attempting to print the array via an %s directive will cause scanf() to read past the end of the array, producing undefined behavior. That the undefined behavior in one case seems reasonable to you and the undefined behavior in the other case does not is irrelevant.
I advise against working with unterminated string-like arrays as you are doing. It would be better to make the arrays large enough for a terminator, and to ensure that they are, in fact, terminated. But if you must print unterminated or possibly unterminated character arrays via printf(), then be sure to use the precision field of the directive to limit the number of characters that may be printed:
#include<stdio.h>
int main(void) {
char c[5];
printf("enter a character\n");
scanf("%5c", c);
printf("%.5s\n", c);
}
You are using the wrong format specifier in scanf for a string.
#include <stdio.h>
int main(void) {
char c[15];
printf("enter a string\n");
scanf("%14s", c); // change %c to %s
printf("%s\n", c);
return 0;
}
Note that the length limit is one less than the array size, to allow room for a nul terminator.
If your input is more than 5 characters then your program will displays 5 characters perfectly and then start displaying garbage value because while printing the string it will print upto '\0' character. And if '\0' is not present at last then it will print garbage.
I want to get the command as input like
<char><number><number>
so is it possible to get it using one scanf() function in c ?
int i,j;
char c;
scanf("%c%d%d",&c, &i, &j);
I don't think that will work because the compiler will consider that as something together rather than one character, and two integers but to take the input in this format i.e. to make the compiler understand that you can take the entire line as a string and then parse the string to extract the character and the integers
char a[1000],c; int x,y;
scanf("%s",a);
c = a[0];
x = a[1] - '0';
y = a[2] - '0';
Also, #BLUEPIXY gave even better solution to your problem!
You can get more than 1 input in 1 scanf as the following:
char ch, string[100];
int number;
printf("--char--/--number--/--string--");
scanf(" %c%d %s",&ch,&number,&string[0]); // -> be careful about the whitespaces
printf("%c\n",ch);
printf("%d\n",number);
printf("%s\n",string);
You dont need to use spaces or \n to enter your input.
i am a learner of 'C' and written a code, but after i compile it, shows a Debug Error message, here is the code:
#include<stdio.h>
void main()
{
int n,i=1;
char c;
printf("Enter Charecter:\t");
scanf("%s",&c);
printf("Repeat Time\t");
scanf("%d",&n);
n=n;
while (i <= n)
{
printf("%c",c);
i++;
}
}
Pls tell me why this happens and how to solve it
The scanf("%s", &c) is writing to memory it should not as c is a single char but "%s" expects its argument to be an array. As scanf() appends a null character it will at the very least write two char to c (the char read from stdin plus the null terminator), which is one too many.
Use a char[] and restrict the number of char written by scanf():
char data[10];
scanf("%9s", data);
and use printf("%s", data); instead of %c or use "%c" as the format specifier in scanf().
Always check the return value of scanf(), which is the number of successful assignments, to ensure subsequent code is not processing stale or uninitialized variables:
if (1 == scanf("%d", &n))
{
/* 'n' assigned. 'n = n;' is unrequired. */
}
scanf("%s",&c); should be scanf("%c",&c);
The %s format specifier tells scanf you're passing a char array. You're passing a single char so need to use %c instead.
Your current code will behave unpredictably because scanf will try to write an arbitrarily long word followed by a nul terminator to the address you provided. This address has memory allocated (on the stack) for a single char so you end up over-writing memory that may be used by other parts of your program (say for other local variables).
I'm not sure you understood the answer to your other question: Odd loop does not work using %c
These format specifiers are each used for a specific job.
If you want to get a:
character from stdin use %c.
string (a bunch of characters) use %s.
integer use %d.
This code:
char c;
printf("Enter Character:\t");
scanf("%c",&c);
Will read 1 character from stdin and will leave a newline ('\n') character there. So let's say the user entered the letter A in the stdin buffer you have:
A\n
The scanf() will pull 'A' and store it in your char c and will leave the newline character. Next it will ask for your int and the user might input 5. stdin now has:
\n5
The scanf() will take 5 and place it in int n. If you want to consume that '\n' there are a number of options, one would be:
char c;
printf("Enter Character:\t");
scanf("%c",&c); // This gets the 'A' and stores it in c
getchar(); // This gets the \n and trashes it
Here is a working version of your code. Please see inline comments in code for fixes:
#include<stdio.h>
void main()
{
int n,i=1;
char c;
printf("Enter Character:\t");
scanf("%c",&c);//Use %c instead of %s
printf("Repeat Time\t");
scanf("%d",&n);
n=n;//SUGGESTION:This line is not necessary. When you do scanf on 'n' you store the value in 'n'
while (i <= n)//COMMENT:Appears you want to print the same character n times?
{
printf("%c",c);
i++;
}
return;//Just a good practice
}