C: Unable to exit program with multiple inputs - c

This code is supposed to exit when I type in EXIT, but when I type EXIT nothing happens, anything I input after it exits the program. Can someone point out what's wrong? Although it works fine when I don't scan multiple inputs.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char cmd[50];
char cmd1[10];
char cmd2[10];
char str;
int x, y, sum;
while(1){
scanf("%s%d%c%d", &cmd ,&x, &str, &y);
if(strstr(cmd,"SUM")){
sum = x + y;
scanf("%s %s",&cmd1, &cmd2);
if((strstr(cmd1,"DSP")) && (strstr(cmd2,"X")))
{
printf("%d\n",sum);
}
else
{
printf(" ");
}
}
else if(strstr(cmd,"EXIT"))
{
break;
}
else
{
printf("INVALID INPUT!\n");
}
}
return 0;
}

It's because of how you use scanf, it will wait for all formats to be read (or it fails).
Instead I suggest you get input using e.g. fgets, then check for command, and if it's e,g. "SUM" then you parse the command arguments.

Related

How to return 0 upon EOF

I have a program that needs to take input until EOF and because this is an assignment, I am constrained to using scanf. I am doing something like this in the main function:
while (1){
int x;
int s=scanf("%d",&x);
if (x==EOF){
break;
}
if(s==0){
fprintf(stderr, "Non integer value input.");
return 1;
}else if(something){...}
}
return 0;
But if I press ^D, the program goes into an infinite loop instead of exiting with 0 and sometimes I just keep seeing ^D on the terminal. How can I fix this?
Another approach I tried looked something like this:
char c;
if (c==EOF){
break;
}
int x=c+0;
PS I also tried doing while(x!=EOF) and while (!EOF) for the loop but that doesn't work either.
Compare the result returned by scanf to EOF, not the out parameter that receives the typed input value.
That is, replace this:
int s = scanf("%d", &x);
if (x == EOF) {
break;
}
With this:
int s = scanf("%d", &x);
if (s == EOF) {
break;
}

Compiler error in C, Error : Expected Expression

I have run into a problem I don't really know how to fix. I mostly code in Python, and this is my first program in C.
#include <stdio.h>
int ask(void) {
scanf("Var");
return 0;
}
int count(ask) {
scanf("number1");
return 0;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
ask();
count(ask());
printf("Thanks!");
printf(%count%);
return 0;
}
However, I keep getting an error.
main.c:22:10: error: expected expression
printf(%count%);
^
main.c:22:17: error: expected expression
printf(%count%);
^
2 errors generated.
compiler exit status 1
What I want it to do is, the user types a number, and then it prints out that number. It's not complete though. I want it to write numbers 1 - the users input, and when it gets the number right, it prints "Your number is:" (number)
The problem (as already pointed out) is that you aren't actually getting and storing the value from the scanf() call. Additionally, printf(%count%) is not valid C syntax. You need to use printf("%d", count).
Putting all that together:
#include <stdio.h>
int ask(void) {
int input_number;
scanf("%d", &input_number);
getchar(); # This is so that the '\n' in is read when you hit Enter
return input_number;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
int input_number = ask();
printf("Thanks!");
printf("The number you entered is %d\n", input_number);
return 0;
}
Some things to read to avoid making mistakes like these:
printf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm
scanf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
You are using incorrect format for printing.
you are using this code printf(%count%); instead you should use this code printf("%d",count(variablename));
Here is the code that you can use:
#include <stdio.h>
int ask(void) {
//scanf("Var");
int var; //declaring integer type varible in C
scanf("%d",&var); //taking input
return var; //returning what is being input by user
}
//int count(ask) //its function you are passing
//so it should have parenthesis
int count( int a )
{
return a;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number: ");
//ask();
count(ask()); // when you will call it will automatically run ask as well
// and it will pass int value that user will input
printf("Thanks!");
int var1=ask(); // this varible var1 will store value returned by ask()
printf("%d",count(var1) ); //this will print that value
//I dont know what you wanted to do here
//maybe you wanted to print value returned by count function
//so it can be done by this
return 0;
}
printf format: printf("%formatspecifier",variable name); Format specifiers are %d for a integer. %f for a floating value. %c for a charcater. s for a string and so on.
In C, we use % to specify output/input type. %d for integer, %f for float, %c for character, %s for string and thats your basic knowledge.
for printf:
printf("%d", varname);
for scanf:
scanf("%d", &varname);
'&' means location in memory.
Your program got many syntax errors, here is some code:
#include<stdio.h>
int ask(){
int varin;
scanf("%d", &varin);
return (varin);
}
int count(int countin){
return (countin); //just an example code, or whatever you wanna do here.
}
int main(){
int out;
printf("Whatever\n");
out = ask();
count(out);
printf("%d", out);
return 0;
}

check input program gets stuck in an infinte loop

I'm trying to create a program that asks to type something and check if it is an integer. If it is an integer, then print "the integer is ...". Else, print "try again" and waits for another input. However, the program prints an infinite number of "try again" if you type in a character. Here's the source code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int inp;
bool t = 1;
printf("type an integer\n");
while (t) {
if (scanf("%i", &inp) == 1) {
printf("The integer is %i", inp);
t = 0;
} else {
printf("try again");
scanf("%i", &inp);
}
}
}
OP's code fail to consume the offending non-numeric input. It remains in stdin, for the next input function. As it is unfortunately just another scanf("%i", &inp) which fails the same way - infinite loop.
After attempting to read an int, read the rest of the line.
#include <stdio.h>
#include <stdbool.h>
int main() {
int inp;
int scan_count;
printf("Type an integer\n");
do {
scan_count = scanf("%i", &inp); // 1, 0, or EOF
// consume rest of line
int ch;
while ((ch == fgetchar()) != '\n' && ch != EOF) {
;
}
} while (scan_count == 0);
if (scan_count == 1) {
printf("The integer is %i\n", inp);
} else {
puts("End of file or error");
}
}
An even better approach would read the line of user input with fgets(). Example
When you entered a char, the variable inp in scanf("%d", &inp) would get null, since the input that doesn't match the format string. And the character you input would remain in the buffer, so that's the reason both your scanf would not stop.
A simplest way to fix this is modify your second scanf("%i", &inp); to scanf("%c", &c); (don't forget to declare a char c in your main function).
check here while(t) its in an infinite loop because you have to set a condition for t something like while(t==1) or while(t>1) or (t<1) something like that. saying while(t) means that t can be anything and it will continue to run.
There is nothing in to break the while loop.
consider getting rid of the boolean, and simply using a while (1) loop with a break. Also you should be using "%d" to indicate an integer in scanf/printf. And there is no need for the scanf call in the else, since your program would loop back and call scanf again anyway.
#include <stdio.h>
int main() {
int inp = 0;
printf("type an integer\n");
while (1) {
if (scanf("%d", &inp) == 1) {
printf("The integer is %d", inp);
break;
}
else {
printf("try again");
}
}
return 0;
}
I hope this helped.

Continue taking input in while loop in c. I've tried fflush

I'm learning data structures in C and I need to take input from the user. I learned from searching other stackoverflow questions that I need to use fflush after I print something.
The issue I'm having is when I type add it doesn't print anything until I break the while loop by entering quit twice. Can someone explain how to fix this and why it happens please?
Here's the code:
#include "stdio.h"
typedef struct S_RacingCar {
char name[8];
int speed;
} RacingCar;
const int MaxCars = 4;
void PrintList() {
printf("List Print...\n");
}
int AddCar(RacingCar *car) {
printf("Enter Name And Speed:\n\n");
char input[16];
fgets( input, 15, stdin);
int ok = 0;
int result = sscanf(input, "%s %d", car->name, car->speed);
if (result == 2) {
ok = 1;
printf("Added:%s Speed:%d\n\n", car->name, car->speed);
fflush(stdout);
} else {
printf("Sorry, error parsing input\n\n");
}
return ok;
}
int main() {
RacingCar allCars[MaxCars];
int numCars = 0;
char command[16];
char input[16];
while( fgets(input, 15, stdin) ){
sscanf(input,"%s",command);
if ( strncmp(command, "quit", 4) == 0){
printf("\n\nBreaking...\n");
break;
} else if ( strncmp(command, "print", 5) == 0){
PrintList();
fflush(stdout);
} else if ( strncmp(command, "add", 3) == 0){
if (numCars < MaxCars) {
numCars += AddCar( &allCars[numCars] );
fflush(stdout);
} else {
printf("Sorry List is Full!!\n\n");
}
}
fflush(stdout);
}
return 0;
}
The output I get after I type print, and then add is:
print
List Print...
add
The cursor is left blinking under add. If I enter quit I get:
print
List Print...
add
quit
Enter Name And Speed:
Sorry, error parsing input
So the program hasn't ended and I'm wondering why. Could someone explain?
To end the program I have to enter quit again:
print
List Print...
add
quit
Enter Name And Speed:
Sorry, error parsing input
quit
Breaking...
<<< Process finished. (Exit code 0)
================ READY ================
The reason that your program behaves weirdly is because it exhibits UB.
Change
int result = sscanf(input, "%s %d", car->name, car->speed);
To
int result = sscanf(input, "%s %d", car->name, &(car->speed));
This is done because sscanf expects an int* but you give it an int.
Also, you can add
setvbuf(stdout, NULL, _IONBF, 0);
at the start of main and remove all the fflush() in your program. The above line flushes the stdout whenever it is written to.
In addition to the other answer, change:
int AddCar(RacingCar *car) {
printf("Enter Name And Speed:\n\n");
to:
int AddCar(RacingCar *car) {
fflush(stdout);
printf("Enter Name And Speed:\n\n");

Dealing with "non-numerical characters" when expecting an integer input

I need a help with the following function, it's expecting an integer input; and when I insert something like "F" (non-numerical characters ), the program gets stuck, it doesn't show any output or let me insert more inputs.
how can this be fixed?
int input_legality(int game_board[FIELD_ROWS][FIELD_COLS])
{
int input=0;
while(1)
{
if(scanf("%d", &input)==1)
{
if(input==DOWN || input==LEFT || input==RIGHT || input==UP)
{
return input;
}
else
if(input==EXIT)
{
printf("\n program exited by user \n");
return 1;
}
else
if(input==PRINT)
{
printField(game_board);
continue;
}
else
{
fprintf(stderr,"your step is undefined, please try another one\n");
continue;
}
}
}
return 0;
}
It seems that "F" is left in stdin if scanf() does not read an integer.
One answer would be to scan a string if an integer is not detected...
Try to add something like
char bla[256];
scanf("%s",bla);
At the end of the while loop (or in case scanf("%d) failed)
Here is a basic "main" code :
#include <stdio.h>
#define DOWN 0
#define UP 1
#define LEFT 2
#define RIGHT 3
#define EXIT 4
#define PRINT 5
int input_legality()
{
int input=0;
while(1)
{
if(scanf("%d", &input)==1)
{
if(input==DOWN || input==LEFT || input==RIGHT || input==UP)
{
return input;
}
else{
if(input==EXIT)
{
printf("\n program exited by user \n");
return 1;
}
else{
if(input==PRINT)
{
printf("ble %d \n",input);
continue;
}
else
{
fprintf(stderr,"your step is undefined, please try another one\n");
continue;
}
}
}
}
//while(getchar() != EOF);
//fflush(stdin);
char bla[256];
scanf("%s", bla);
}
return 0;
}
int main ( int argc , char * argv [] )
{
int i;
for(i=0;i<42;i++){
input_legality();
}
return 0;
}
This scanf is the easy way : some other may be better.
Using switch-case may clarify the code.
Bye,
Francis
Always, always, always get (interactive) input a line at a time. That's how the user conceives it, so the program logic should be similar.
The POSIX getline function is very useful. Alternatively, you can use fgets and deal with overlong lines yourself (perhaps implementing getline, since it is pretty easy).
Once you've fetched a line of input, parse it (being sure to error on trailing garbage) using any method: sscanf, strtok_r, strtou?ll?, ...

Resources