I am creating a very basic calculator in C but the output is not coming as desired.
#include<stdio.h>
int main(int argc, char const *argv[])
{
/* code */
char ch;
int a,b,p=0;
scanf("%d",&a);
while(1)
{
ch=getchar();
if(ch==';')
{
p=2;
break;
}
scanf("%d",&b);
if(ch=='+')
{
a+=b;
}
if(ch=='-')
{
a-=b;
}
if(ch=='*')
{
a*=b;
}
if(ch=='/' && b!=0)
{
a/=b;
}
if(ch=='/' && b==0)
{
printf("INVALID INPUT\n");
p=2;
break;
}
}
if(p!=0)
printf("%d",a);
return 0;
}
The Output is always coming as the initial value which has been assigned to "a".
Output which is coming-
4
+
5
;
4
Expected output -
4
+
5
;
9
Can you please help me with this issue of why the expression is not getting evaluated correctly?
The line
scanf("%d",&a);
will consume the first number from the input stream, but it will leave the newline character on the input stream.
Therefore, when you later call
ch=getchar();
it will read that newline character. It will not read the + character.
If you want to read the + character, then you can change that line to the following:
scanf( " %c", &ch );
This line will first discard all whitespace characters and will match the first non-whitespace character on the input stream.
Afterwards, your program will have the desired output:
4
+
5
;
9
An alternative solution would be to discard the rest of the line after every call to scanf that uses the %d format specifier. That way, calling getchar immediately afterwards should read the + character as intended.
You can discard the remainder of an input line using the following code:
//discard remainder of input line
{
int c;
do
{
c = getchar();
} while ( c != EOF && c != '\n' );
}
Here is a more compact way of writing the same thing:
//discard remainder of input line
for ( int c; (c=getchar()) != EOF && c != '\n'; )
;
The only problem is in scanning the inputs.
As a tab or a new line must seperate the value supplied to scanf.
In short, just add \n at the end of scanf.
scanf("%d\n", &a);
scanf("%d\n", &b);
this should do it.
Related
I'm trying to make a function that reads ints from stdin. it has to read until a certain amount of numbers is read (count in example below), or until it finds a '\n'.
Since as far as I am aware scanf (with %d format specifier) ignores newlines, I used getchar and converted the character into the number it should be.
this works but only for 1 digit numbers.
is there any better way to achieve this?
This is my code:
char num = getchar();
while (num != '\n' && count < 9) {
//boring operations that don't matter
num = getchar()
}
Reading via fgets() is better. Continue reading if your must use scanf().
To use scanf("%d",...), we need extra care to read a line. As "%d" consumes leading white-space, including '\n', we need more code to look for white-space and test if a '\n' is found.
int count = 0;
while (count < 9) {
// Read leading spaces
int ch;
while (isspace((c = getchar())) && c != '\n') {
;
}
if (c == '\n' || c == EOF) break; // We are done reading
ungetc(c, stdin); // put character back
int some_int;
if (scanf("%d", &some_int) == 1) {
printf("Integer found %d\n", some_int);
count++;
} else {
// Non-numeric input, consume at least 1 character.
getchar();
}
}
If numeric text is outside the range of int, the above use of "%d" is undefined behavior. For robust code, use fgets().
The %d conversion specifier only ignores leading whitespace. So you can do something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 10) : 10;
int x;
while( n-- && scanf("%d%*[ \t]", &x) == 1 ){
printf("Read: %d\n", x);
int c = getchar();
if( c == EOF || c == '\n' ){
break;
}
ungetc(c, stdin);
}
return 0;
}
However, this will probably not handle a stream like 10 5 x in a reasonable way. You'll need more logic on the first non-whitespace after an integer to handle that (maybe just do if( c == EOF || ! isdigit(c) ){ break; }). Parsing data with scanf if fickle (it really never has a purpose outside of university exercises). Just use fgets and strtol.
scanf() doesn't ignore \n
#include <stdio.h>
#include <stddef.h>
int main(int argc , char *argv[])
{
int b;
char c;
scanf("%d%c",&b,&c);
if(c == '\n') printf("and then " );
}
Someone posted an answer and then deleted but it was the perfect solution for my problem, so all credit to the original author.
The solution was reading normally with scanf and afterwards,with getchar, checking if it was \n or EOF. If it was break out of the cycle, if it wasn't, "unread" with ungetc so you can scanf the number in the next iteration.
So my final code looks like this:
while(scanf("%d",&num) == 1 && count<9){
//boring operations
c = getchar();
if (c == EOF || c == '\n') break;
if (ungetc(c,stdin) == EOF) break;
}
NOTE: like Andrew Henle pointed out in the replies, this doesn't work unless it is guaranteed that there isn't any space between the digits and the newline
I am learning C and I am trying to use fgets() and strtol() to accept user input and just take the first character. I am going to make a menu that will allow a user to select options 1-3 and 4 to exit. I want each option to only be selected if '1', '2', '3', or '4' are selected. I don't want 'asdfasdf' to work. I also don't want '11212' to select the first option since it starts with a 1. I created this code so far while I started testing and for some reason this loops over the question and supplies a 0 to the input.
#include <stdio.h>
#include <stdlib.h>
int main() {
char a[2];
long b;
while(1) {
printf("Enter a number: ");
fgets(a, 2, stdin);
b = strtol(a, NULL, 10);
printf("b: %d\n", b);
}
return 0;
}
output
Enter a number: 3
b: 3
Enter a number: b: 0
Enter a number:
It should be:
Enter a number: 3
b: 3
Enter a number: 9
b: 9
You need to have enough room for the '\n' to be read or else it will be left in the input buffer and the next iteration it will be read immediately and thus make fgets() return with an empty string and hence strtol() returns 0.
Read fgets()'s documentation, it reads until a '\n' or untill the buffer is full. So the first time, it stops because it has no more room to store characters, and then the second time it still has to read '\n' and it stops immediately.
A possible solution is to increase the buffer size, so that the '\n' is read and stored in it.
Another solution, is to read all remaining characters after fgets().
The second solution could be cleanly implemented by reading one character at a time instead, since you are just interested in the first character you can discard anything else
#include <stdio.h>
#include <stdlib.h>
int main()
{
int chr;
while (1) {
// Read the next character in the input buffer
chr = fgetc(stdin);
// Check if the value is in range
if ((chr >= '0') && (chr <= '9')) {
int value;
// Compute the corresponding integer
value = chr - '0';
fprintf(stdout, "value: %d\n", value);
} else {
fprintf(stderr, "unexpected character: %c\n", chr);
}
// Remove remaining characters from the
// input buffer.
while (((chr = fgetc(stdin)) != '\n') && (chr != EOF))
;
}
return 0;
}
this code should read a positive number and if user enter a non-numeric value, it asking him again to enter a number and wait the input to check again till entering a number
do
{
printf("Enter a positive number: ");
}
while ( (scanf("%d%c", &n,&c) != 2 || c!='\n' || n<0) ) ;
but actually when entering non-numeric it keeps doing the body of the while loop without reading the waiting to check the condition of the while loop while(scanf("%d%c", &n,&c) != 2 || c!='\n' || n<0)
when edit the condition to
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
do
{
printf("Enter a positive number: ");
}
while ( (scanf("%d%c", &n,&c) != 2 || c!='\n' || n<0) && clean_stdin() ) ;
It executes in the right way, but I don't understand why we need to add getchar() although we already use scanf() in the condition
When scanf("%d%c", ... encounters non-numeric input, the "%d" causes the scanning to stop and the offending character to remain in stdin for the next input function. The "%c" does not get a chance to read that non-numeric character.
If code re-reads stdin with the same scanf("%d%c", ..., the same result. Some other way is needed to remove the non-numeric input. getchar(), getch(), etc. will read any 1 character.
Example code GetPositiveNumber()
Consider using fgets to collect input. Any invalid input is already removed from the input stream making it simpler to try again.
Parse the input with sscanf or others as needed.
char input[40] = "";
int valid = 0;
int n = 0;
do {
printf ( "Enter a positive integer\n");
if ( fgets ( input, sizeof ( input), stdin)) {
int last = 0;
if ( 1 == ( valid = sscanf ( input, "%d%n", &n, &last))) {
if ( n < 0 || input[last] != '\n') {
valid = 0;//reset if negative or last is not newline
}
}
}
else {
fprintf ( stderr, "problem getting input from fgets\n");
return 0;
}
} while ( valid != 1);
Because scanf() with most specifiers ignores white spaces, and you need to collect them before calling scanf() again if a '\n' is left in the buffer. If you don't collect them (and discard them immediately), then scanf() will return immediately on the next call.
See this code
#include <stdio.h>
int
main(int argc, char* argv[]) {
char c = 0;
scanf("%c", &c);
printf("%c\n", c);
scanf("%c", &c);
printf("%c\n", c);
return 0;
}
If you type over two or three characters, second call of scanf doesn't work as interructive. And getch() is not standard. Also you shouldn't call getchar() since it may block. You can use fseek.
Hack using fseek works only on Windows. :-(
BAD SOLUTION
#include <stdio.h>
int
main(int argc, char* argv[]) {
char c = 0;
scanf("%c", &c);
printf("%c\n", c);
fseek(stdin, 0, SEEK_END);
scanf("%c", &c);
printf("%c\n", c);
return 0;
}
GOOD SOLUTION
#include <stdio.h>
int
main(int argc, char* argv[]) {
char buf[BUFSIZ];
char c = 0;
scanf("%c", &c);
printf("%c\n", c);
while (!feof(stdin) && getchar() != '\n');
scanf("%c", &c);
printf("%c\n", c);
return 0;
}
This works good on Windows & Linux
In this program I have taken a dimensional character array of size[3][4],
as long as I enter a 3 characters for each row it will work well.
For example: if I enter abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.
How should I check for null character in 2 dimensional?
# include <stdio.h>
#include <conio.h>
# include <ctype.h>
void main()
{
int i=0;
char name[3][4];
printf("\n enter the names \n");
for(i=0;i<3;i++)
{
scanf( "%s",name[i]);
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
getch();
}
As pointed out by #SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.
You can do this:
printf("\n enter the names \n");
for(i = 0; i < 3; i++) {
int c;
scanf("%3s", name[i]);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
How should I chk for null character in 2 dimensional ... [something has eaten the rest part, I guess]
You don't need to, at least not in current context.
The problem is in your approach of allocating memory and putting input into it. Your code has
char name[3][4];
if you enter more that three chars, you'll be overwriting the boundary of allocated memory [considering the space of \0]. You've to limit your scanf() using
scanf("%3s",name[i]);
Note:
change void main() to int main(). add a return 0 at the end.
always check the return value of scanf() to ensure proper input.
EDIT:
As for the logical part, you need to eat up the remainings of the input words to start scanning from the beginning of the next word.
Check the below code [Under Linux, so removed conio.h and getch()]
# include <stdio.h>
# include <ctype.h>
int main()
{
int i=0; char name[3][4];
int c = 0;
printf("\n enter the names \n");
for(i=0;i < 3;i++)
{
scanf( "%3s",name[i]);
while(1) // loop to eat up the rest of unwanted input
{ // upto a ' ' or `\n` or `EOF`, whichever is earlier
c = getchar();
if (c == ' ' || c == '\n' || c == EOF) break;
}
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
return 0;
}
(Cringing after reading the answers to date.)
First, state the problem clearly. You want to read a line from stdin, and extract three short whitespace separated strings. The stored strings are NUL terminated and at most three characters (excluding the NUL).
#include <stdio.h>
void main(int, char**) {
char name[3][4];
printf("\n enter the names \n");
{
// Read tbe line of input text.
char line[80];
if (0 == fgets(line, sizeof(line), stdin)) {
printf("Nothing read!\n");
return 1;
}
int n_line = strlen(line);
if ('\n' != line[n_line - 1]) {
printf("Input too long!\n");
return 2;
}
// Parse out the three values.
int v = sscanf(line, "%3s %3s %3s", name[0], name[1], name[2]);
if (3 != v) {
printf("Too few values!\n");
return 3;
}
}
// We now have the three values, with errors checked.
printf("you entered these names\n%s\n%s\n%s\n",
name[0], name[1], name[2]
);
return 0;
}
you might consider something on the order of scanf( "%3s%*s",name[i]);
which should, if I recall correctly, take the first three characters (up to a whitespace) into name, and then ignore anything else up to the next white space. This will cover your long entries and it does not care what the white space is.
This is not a perfect answer as it will probably eat the middle entry of A B C if single or double character entries are mode. strtok, will separate a line into useful bits and you can then take substrings of the bits into your name[] fields.
Perhaps figuring out the entire requirement before writing code would be the first step in the process.
How should i exit out of a loop just by hitting the enter key:
I tried the following code but it is not working!
int main()
{
int n,i,j,no,arr[10];
char c;
scanf("%d",&n);
for(i=0;i<n;i++)
{
j=0;
while(c!='\n')
{
scanf("%d",&arr[j]);
c=getchar();
j++;
}
scanf("%d",&no);
}
return 0;
}
I have to take input as follows:
3//No of inputs
3 4 5//input 1
6
4 3//input 2
5
8//input 3
9
Your best bet is to use fgets for line based input and detect if the only thing in the line was the newline character.
If not, you can then sscanf the line you've entered to get an integer, rather than directly scanfing standard input.
A robust line input function can be found in this answer, then you just need to modify your scanf to use sscanf.
If you don't want to use that full featured input function, you can use a simpler method such as:
#include <stdio.h>
#include <string.h>
int main(void) {
char inputStr[1024];
int intVal;
// Loop forever.
for (;;) {
// Get a string from the user, break on error.
printf ("Enter your string: ");
if (fgets (inputStr, sizeof (inputStr), stdin) == NULL)
break;
// Break if nothing entered.
if (strcmp (inputStr, "\n") == 0)
break;
// Get and print integer.
if (sscanf (inputStr, "%d", &intVal) != 1)
printf ("scanf failure\n");
else
printf ("You entered %d\n", intVal);
}
return 0;
}
There is a difference between new line feed (\n or 10 decimal Ascii) and carriage return (\r or 13 decimal Ascii).
In your code you should try:
switch(c)
{
case 10:
scanf("%d",&no);
/*c=something if you need to enter the loop again after reading no*/
break;
case 13:
scanf("%d",&no);
/*c=something if you need to enter the loop again after reading no*/
break;
default:
scanf("%d",&arr[j]);
c=getchar();
j++;
break;
}
You also should note that your variable c was not initialized in the first test, if you don't expected any input beginning with '\n' or '\r', it would be good to attribute some value to it before the first test.
change
j=0;
to
j=0;c=' ';//initialize c, clear '\n'
When the program comes out of while loop, c contains '\n' so next time the program cannot go inside the while loop. You should assign some value to c other than '\n' along with j=0 inside for loop.