How to scan enter key as input - c

I am trying to learn c Language, and I have to create a calculator, the thing is, if I don't type anything and press the enter key it should print out an error, I have tried to do it with scanf but it is not working.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float a,b,c;
char op;
int q=1;
while(q=1){
scanf("%f%c%f",&a,&op,&b);
if (scanf("%f%c%f",&a,&op,&b)=='\n')
{
printf("error");
}
switch (op)
{
case '+':c=a+b;
break;
case '-':c=a-b;
break;
case'*':c=a*b;
break;
case'/':c=a/b;
break;
default:printf("error");
q=2;
break;
}
{printf("%f\n",c);}
}}

Try to scan for a newline using a scanset %1[\n].
Another scanset %*[^\n] will scan and discard everything that is not a newline.
Another approach would be to use fgets to read a line and then parse the line with sscanf.
#include <stdio.h>
#include <stdlib.h>
int main ( void) {
char newline[2] = "";
char op = 0;
int scanned = 0;
double a = 0.0;
double b = 0.0;
double c = 0.0;
while ( 1) {
printf ( "input a number, an operator and a number\n");
printf ( " or just enter to quit\n");
if ( 1 == scanf ( "%1[\n]", newline)) { // try to scan a newline
printf ( "done\n");
break;
}
if ( 3 != ( scanned = scanf("%lf %c%lf", &a, &op, &b))) {
printf ( "bad input error\n");
printf ( "try again\n");
}
if ( EOF == scanned) {
printf ( "EOF error\n");
break;
}
scanf ( "%*[^\n]"); // scan and discard up to newline
scanf ( "%1[\n]", newline); // scan a newline
if ( 3 == scanned) {
switch (op) {
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
break;
default:
printf ( "bad op error\n");
printf ( "try again\n");
op = 0;
break;
}
if ( op) {
printf ( "%f\n", c);
}
}
}
return 0;
}

Related

How can I reprogram this in such a way that, that I don't need to use any sort of variable?

This my code:
#include <stdio.h>
#include <conio.h>
int processChoice()
{
int choice = -1; //I need to execute this code without using any variable
printf("\nMake a Choice (1, 2, 3 or 0): ");
scanf("%d",&choice);
printf("%d",choice);
switch(choice)
{
case 0:
printf("\nExiting...\n");
break;
case 1:
printf("\nDrawing rectangle...\n");
break;
case 2:
printf("\nDrawing Right triangle...\n");
break;
case 3:
printf("\nDrawing isosceles triangle...\n");
break;
default:
printf("\n** Invalid Choice! **\n");
choice = -1;
}
return choice;
}
void showMenu()
{
printf("\nMenu:");
printf("\n1. Draw Rectangle");
printf("\n2. Draw Right triangle");
printf("\n3. Draw isosceles triangle");
printf("\n0. Exit program\n");
}
int main()
{
int x = -1;
do
{
showMenu();
}while(processChoice() != 0);
return 0;
}
That's my code here I used a variable "int Choice = -1;" I'm supposed to execute the same code without using any variable as per guidelines of my mentor.
I'm expecting the same code to be executed without using any variable.
Maybe your mentor means that this declaration in main
int x = -1;
is not used and should be removed.
As for the function processChoice then in any case you need to enter a value from the user. I see the only possibility to write the function without using a variable the following way with using function getchar
int processChoice( void )
{
printf("\nMake a Choice (1, 2, 3 or 0): ");
switch( getchar() )
{
case '0':
printf("\nExiting...\n");
while ( getchar() != '\n' );
return 0;
case '1':
printf("\nDrawing rectangle...\n");
while ( getchar() != '\n' );
return 1;
case '2':
printf("\nDrawing Right triangle...\n");
while ( getchar() != '\n' );
return 2;
case '3':
printf("\nDrawing isosceles triangle...\n");
while ( getchar() != '\n' );
return 3;
default:
printf("\n** Invalid Choice! **\n");
while ( getchar() != '\n' );
return -1;
}
}

Do while can do this but I want to know why this is wrong

#include <stdio.h>
#include <rpcndr.h>
int main() {
boolean playAgain=1;
char playInput;
float num1,num2,answer;
char operator;
while (playAgain){
printf("Enter First Number, operator, second number:");
scanf("%f%c%f",&num1,&operator,&num2);
switch (operator) {
case '*':
answer=(num1*num2);
break;
case '/':
answer=(num1/num2);
break;
case '+':
answer=num1+num2;
break;
case '-':
answer=num1-num2;
break;
default:break;
}
printf("%f\n",answer);
printf("Do You Want To Try It Again(y/n)?");
scanf("%c",&playInput);
if(playInput=='n'){
playAgain=0;
}
}
}
Do while can do this code. But I want to why this method gets an error. And there is a problem with Scanf() function.
Error says :
Clang-Tidy: 'scanf' used to convert a string to a floating-point value, but function will not report conversion errors; consider using 'strtof' instead
There are some issues.
The first scanf won't check for syntax errors in the numbers and may leave a newline in the stream and confuse the second scanf
The second scanf may not strip the newline from the stream, so on the second loop iteration, the first scanf may have a problem.
While it might be possible to fix/contort scanf into doing what you want, I'd follow clang's warning and use strtof.
Here's the code refactored to use fgets and strtof. It is annotated:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <rpcndr.h>
// lineget -- get a line from user with prompt
// RETURNS: pointer to buffer (NULL means EOF)
char *
lineget(char *buf,size_t len,const char *prompt)
{
char *cp;
// output prompt to user
puts(prompt);
fflush(stdout);
do {
// get an input line
cp = fgets(buf,len,stdin);
// got EOF
if (cp == NULL)
break;
// strip newline
buf[strcspn(buf,"\n")] = 0;
} while (0);
return cp;
}
int
main(void)
{
float num1, num2, answer;
char *cp;
char buf[1000];
int err;
char operator;
while (1) {
cp = lineget(buf,sizeof(buf),
"Enter First Number, operator, second number:");
if (cp == NULL)
break;
// get the first number
num1 = strtof(cp,&cp);
// get the operator
// NOTE: this could be a syntax error for the first number -- we'll
// check that below in the switch
operator = *cp;
if (operator != 0)
++cp;
// get second number and check for syntax error
num2 = strtof(cp,&cp);
if (*cp != 0) {
printf("ERROR trailing '%s'\n",cp);
continue;
}
err = 0;
switch (operator) {
case '*':
answer = (num1 * num2);
break;
case '/':
answer = (num1 / num2);
break;
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
default:
err = 1;
break;
}
// we got a bad operator (or syntax error in first number)
if (err) {
printf("ERROR unknown operator '%c'\n",operator);
continue;
}
printf("%f\n", answer);
cp = lineget(buf,sizeof(buf),"Do You Want To Try It Again(y/n)?");
if (cp == NULL)
break;
if (buf[0] == 'n')
break;
}
return 0;
}
UPDATE:
The above code will detect most errors. Here's an enhanced version that does even more explicit checking:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <rpcndr.h>
// lineget -- get a line from user with prompt
// RETURNS: pointer to buffer (NULL means EOF)
char *
lineget(char *buf,size_t len,const char *prompt)
{
char *cp;
// output prompt to user
puts(prompt);
fflush(stdout);
do {
// get an input line
cp = fgets(buf,len,stdin);
// got EOF
if (cp == NULL)
break;
// strip newline
buf[strcspn(buf,"\n")] = 0;
} while (0);
return cp;
}
int
main(void)
{
float num1, num2, answer;
char *cp;
char *bp;
char buf[1000];
int err;
char operator;
while (1) {
bp = lineget(buf,sizeof(buf),
"Enter First Number, operator, second number:");
if (bp == NULL)
break;
// get the first number
num1 = strtof(bp,&cp);
// ensure we got at least a digit
// NOTE: this will detect:
// ""
// "j"
if (cp == bp) {
printf("ERROR no first number specified\n");
continue;
}
// get the operator
// NOTE: this could be a syntax error for the first number -- we'll
// check that below in the switch
operator = *cp;
// no operator specified
if (operator == 0) {
printf("ERROR no operator specified\n");
continue;
}
// skip over the operator
bp = ++cp;
// get second number and check for syntax error
num2 = strtof(bp,&cp);
if (*cp != 0) {
printf("ERROR trailing '%s'\n",cp);
continue;
}
// we need at least one digit (e.g.):
// we want to reject: 23+ and ensure we have [at least] 23+0
// this will detect 23+k
if (cp == bp) {
printf("ERROR no second number specified\n");
continue;
}
err = 0;
switch (operator) {
case '*':
answer = (num1 * num2);
break;
case '/':
answer = (num1 / num2);
break;
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
default:
err = 1;
break;
}
// we got a bad operator (or syntax error in first number)
if (err) {
printf("ERROR unknown operator '%c'\n",operator);
continue;
}
printf("%f\n", answer);
cp = lineget(buf,sizeof(buf),"Do You Want To Try It Again(y/n)?");
if (cp == NULL)
break;
if (buf[0] == 'n')
break;
}
return 0;
}
EDIT:
fflush is undefined behavior, you can use getchar() to clear the buffer
#include <stdio.h>
void clear_input_buffer()
{
char tmp;
do
{
tmp = getchar();
} while (tmp != '\n' && tmp != EOF);
}
int main()
{
_Bool playAgain = 1;
char playInput;
float num1, num2, answer;
char operator;
while (playAgain)
{
printf("Enter First Number, operator, second number:");
scanf("%f%c%f", &num1, &operator, & num2);
clear_input_buffer();
switch (operator)
{
case '*':
answer = (num1 * num2);
break;
case '/':
answer = (num1 / num2);
break;
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
default:
break;
}
printf("%f\n", answer);
printf("Do You Want To Try It Again(y/n)?");
scanf("%c", &playInput);
clear_input_buffer();
if (playInput == 'n')
{
playAgain = 0;
}
}
}
OLD:
You should use fflush(stdin) (if your compiler supports it, it is undefinded by c stanard) or a diffrent method to clear the input buffer, otherwise scanf will read an extra \n at the end causing it to skip the rest of the data in the buffer
#include <stdio.h>
int main() {
_Bool playAgain=1;
char playInput;
float num1,num2,answer;
char operator;
while (playAgain){
printf("Enter First Number, operator, second number:");
scanf("%f%c%f",&num1,&operator,&num2);
fflush(stdin);
switch (operator) {
case '*':
answer=(num1*num2);
break;
case '/':
answer=(num1/num2);
break;
case '+':
answer=num1+num2;
break;
case '-':
answer=num1-num2;
break;
default:break;
}
printf("%f\n",answer);
printf("Do You Want To Try It Again(y/n)?");
scanf("%c",&playInput);
fflush(stdin);
if(playInput=='n'){
playAgain=0;
}
}
}

Calculator with Decimal, Octal and Hexadecimal Numbers

I want to make a calculator that is capable of calculation with decimal numbers and is able to return the decimal values in their respective binary, octal or hexadecimal representation.
So far in the main method the program reads the command line and I can invoke the program by two ways.
The first way would be with 3 values:
"number1" "operator" "number2".
And the second way would be with 4 values:
"wished numeral system for the output" "number1" "operator" "number2".
Where for the wished numeral system output b would stand for for binary, o for octal and h for hexadecimal. In both ways the user should be able to input decimal, octal and hexadecimal numbers for the inputs number1 and number2.
#include "zahlen.h"
#include <stdio.h>
#include "stringTOint.h"
int main(int argc, char *argv[]) {
char o,op,sx[DIGITS+1],sy[DIGITS+1],sz[DIGITS+1];
int x,y,z;
char flag_x,flag_y;
/* 1) Read Commandline */
if (argc != 4 && argc != 5) {
printf("Aufruf: %s -o <x> <op> <y> \n",argv[0]);
return 1;
} else if(argc == 4) {
x = stringTOint(argv[1]);
op = argv[2][0];
y = stringTOint(argv[3]);
} else if(argc == 5) {
o = argv[1][0];
x = stringTOint(argv[2]);
op = argv[3][0];
y = stringTOint(argv[4]);
if(o != 'b' && o != 'o' && o != 'h') {
printf("Wrong Operation\n");
return 1;
}
}
/* 2) Solve the equation */
if(argc==4) {
printf("solve: %s %c %s \n", argv[1], op, argv[3]);
z = solve(x, op, y);
} else if(argc==5) {
printf("solve: %s %c %s \n", argv[2], op, argv[4]);
z = solve(x, op, y);
}
/* 3) Calculate the Representation of the wished Numeral System */
switch(o) {
case 'b':
intTObinaer(x, sx);
intTObinaer(y, sy);
intTObinaer(z, sz);
break;
case 'o':
intTOoctal(x,sx);
intTOoctal(y,sy);
intTOoctal(z,sz);
break;
case 'h':
intTOhexal(x,sx);
intTOhexal(y,sy);
intTOhexal(z,sz);
break;
default:
intTObinaer(x, sx);
intTObinaer(y, sy);
intTObinaer(z, sz);
break;
}
/* 4) Return the results */
printf("\n %s %d\n%c %s %d\n= %s %d\n", sx,x,op,sy,y,sz,z);
return 0;
}
The methods intTObinaer, intTOoctal and intTOhexal only differ by the base with which the decimal number gets divided.
intTObinaer(int i, char str[]) {
unsigned int zahl = i;
int j;
/* Fill Array with zeros */
int x = 0;
for (x; x < DIGITS+1; x++) {
str[x] = '0';
}
/*Calculate the Binary representation of the given Decimal integer */
for (j = DIGITS-1; j > 0; j--) {
/* This base gets changed to 8 or 16 for octal and hexal representation */
str[j] = (char) (zahl % 2) + '0';
zahl = zahl / 2;
if (zahl == 0) {
break;
}
}
/* Set the end of the Array */
str[DIGITS] = '\0';
}
The actual equation gets solved in the solve method, where the right operation for number1 and number2 gets chosen by an switchcase where the different cases can be selected by the char op that the user had input between the two numbers.
#include <stdio.h>
int solve(int x, char op, int y) {
int ergebnis = 0;
switch(op) {
case '+':
ergebnis = x + y;
break;
case '-':
ergebnis = x - y;
break;
case '*':
ergebnis = x * y;
break;
case '/':
ergebnis = x / y;
break;
case '&':
ergebnis = x & y;
break;
case '|':
ergebnis = x | y;
break;
default:
printf("Wrong input\n");
}
return ergebnis;
}
My question now is due to the fact the the user should be able to input different numeral systems(e.g. decimal, octal or hexadecimal) how can I identify the different numeral systems and then transfer them into decimal so that I can calculate the result. After that these decimal Numbers have to be converted back into the desired numeral system that the user wanted.
Looks like you only need to add two lines to do that:
#include "stdlib.h"
#define stringTOint(arg) ((int)strtol(arg,NULL,0))
Or better yet, replace those invocations of stringTOint() with corresponding strtol() invocations (and add the #include, of course).
strtol() uses the same prefixes as for C literals: 0 for octal, 0x for hex, no prefix is decimal.
I would like to suggest another approach to this problem.
Many of the parsing you perform can be performed directly by the sscanf function, the only case is the binary case that needs to be implemented differently.
The implementation follows 3 main step:
Parse the input using the sscanf function (or the ConvCharToBinfor binary values) and store the values in the variables a and b;
Perform the operation and store the result in the res variable;
Print the output result by using the printf parsing (or loop for the binary case).
An implementation would be the following:
#include<stdio.h>
#include<string.h>
typedef struct stack {
unsigned char data[32];
int size;
} stack_t;
int ConvCharToBin(char* input);
int main(int argc, char *argv[]) {
char numSys = 'd', op;
char** param = argv;
int a, b, res;
param++;
//error case
if(argc != 4 && argc != 5) {
//not a valid input
printf("Not a valid input");
return -1;
}
if(argc == 5) {
numSys = param[0][0];
param++;
}
op = param[1][0];
switch(numSys) {
case 'b':
a = ConvCharToBin(param[0]);
b = ConvCharToBin(param[2]);
break;
case 'd':
sscanf(param[0], "%d", &a);
sscanf(param[2], "%d", &b);
break;
case 'h':
sscanf(param[0], "%x", &a);
sscanf(param[2], "%x", &b);
break;
case 'o':
sscanf(param[0], "%o", &a);
sscanf(param[2], "%o", &b);
break;
default:
//no viable number system
return -1;
}
switch(op) {
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '/':
res = a / b;
break;
case '*':
res = a * b;
break;
case '&':
res = a & b;
break;
case '|':
res = a | b;
break;
default:
//no valid operand
printf("invalid operation\n");
return -1;
}
stack_t tmp;
tmp.size = 0;
int i;
switch(numSys) {
case 'b':
while (res) {
if (res & 1) {
tmp.data[tmp.size] = '1';
tmp.size++;
} else {
tmp.data[tmp.size] = '0';
tmp.size++;
}
res >>= 1;
}
for(i = tmp.size - 1; i >= 0; i--) {
printf("%c", tmp.data[i]);
}
printf("\n");
break;
case 'd':
printf("%d\n", res);
break;
case 'h':
printf("%x\n", res);
break;
case 'o':
printf("%o\n", res);
break;
}
return 0;
}
int ConvCharToBin(char* input) {
char* idx;
int res = 0x00000000;
for(idx = input; idx < input + strlen(input); idx++) {
res <<= 1;
if(*idx == '1') {
res |= 0x00000001;
}
}
return res;
}
The sscanf reads formatted data from a string (in you case the argv strings)
This can be parsed using the following:
%d for decimal;
%x for hexadecimal;
%o for octal.
Unfortunately there is no C standard for parsing binary using sscanf, so this is done apart using the stdout.
I would also point out that this implementation has two limitation
Input/output limited to 32 bit unsigned (so from 0 to 4294967295), but with some slight modifications it can be extended;
No error checking for the input values, this can also be easily implemented.

Problems with running a Program with files

I have a school project and that project is making a C programming dictionary which will contain basic C statements and their meanings and uses. These statements and meanings will be inputted by me. Whatever I input will be stored in the file Dictionary.dat.
#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct
{
char word[30], meaning[1000];
}lib;
void intro(void);
void updateword(FILE*,lib);
void addword(FILE*,lib);
void showMeaning(FILE*,lib);
void letter(FILE*,lib);
void showAll(FILE*,lib);
int main()
{
char pass[8], choice;
lib a;
FILE *f=fopen("Dictionary.dat","a+b");
printf("Enter Admin code: ");
gets(pass);
if(strcmp(pass,"turla")==0)
{
printf("Welcome to Admin page\n");
printf("What will do?\n(U)-update\t(A)-Add Word\n(S)-Show All\t");
printf("(L)-Show by Letter\n(M)-Show Meaning\n");
while(choice!='E'||choice!='e')
{
scanf("%c",&choice);
if(f!=NULL)
{
switch(choice)
{
case 'U': updateword(f,a);break;
case 'A': addword(f,a);break;
case 'S': showAll(f,a);break;
case 'L': letter(f,a);break;
case 'M': showMeaning(f,a);break;
case 'E': printf("closing");break;
}
}
}}
else
{
printf("W e l c o m e t o C P r o g r a m m i n g D i c t i o n a r y !\n");
printf("\t A Dictionary for C programming terms\n\n");
printf("What would you want to do? do?\n\n (S)-Search terms\t(L)-Search by letter\n(A)-Show All\n");
scanf("%c",&choice);
while(choice!='E'||choice!='e')
{
intro();
switch(choice)
{
case 'A':
case 'a': showAll(f,a); break;
case 'L':
case 'l': letter(f,a); break;
case 'S':
case 's': showMeaning(f,a); break;
case 'E':
case 'e': printf("closing..."); break;
}
}
system("cls");
}
fclose(f);
getch();
return 0;
}
void intro(void)
{
printf("W e l c o m e t o C P r o g r a m m i n g D i c t i o n a r y !\n");
printf("\t A Dictionary for C programming terms\n\n");
printf("What would you want to do? do?\n\n (S)-Search terms\t(L)-Search by letter\n(A)-Show All\n");
}
void updateword(FILE*ptr,lib a)
{
char srchWrd[30],choice,qtn='Y';
printf("Enter Word to update: ");
gets(srchWrd);
while(fread(&a,sizeof(lib),1,ptr))
{
system("cls");
if(strcmp(srchWrd,a.word)==0)
{
printf("What will you change? (W)-Word (M)-Meaning");
scanf("%c",&choice);
while(qtn!='N'||qtn!='n')
{
switch(choice)
{
case 'W':
case 'w': gets(a.word); printf("Do you still want to edit?(Y/N): "); scanf("%c",&qtn); break;
case 'M':
case 'm': gets(a.meaning); printf("Do you still want to edit?(Y/N): "); scanf("%c",&qtn); break;
default: printf("Invalid option. Enter Again");
}
}
fseek(ptr,sizeof(lib)*-1,1);
fwrite(&a,sizeof(lib),1,ptr);
}}
}
void addword(FILE*ptr,lib a)
{
printf("Enter word: ");fflush(stdin);
gets(a.word);
printf("Enter Meaning: ");fflush(stdin);
gets(a.meaning);
fwrite(&a,sizeof(lib),1,ptr);
}
void showMeaning(FILE*ptr,lib a)
{
char wrd[30];
int ctr=0;
printf("Search: ");
gets(wrd);
while(fread(&a,sizeof(lib),1,ptr))
{
if(strcmp(wrd,a.word)==0)
{
printf("\t%s",a.meaning);
ctr ++;
}
}
if(ctr==0)
printf("No word or symbol found in Dictionary");
}
void letter(FILE*ptr,lib a)
{
char ltr;
int ctr;
printf("Enter Letter");
scanf("%c",&ltr);
while(fread(&a,sizeof(lib),1,ptr))
{
if(ltr==a.word[0])
{
printf("%s - %s",a.word,a.meaning);
ctr++;
}
}
if(ctr==0)
printf("No search results");
}
void showAll(FILE*ptr,lib a)
{
while(fread(&a,sizeof(lib),1,ptr))
printf("%s - %s",a.word,a.meaning);
}
I have problems inputting the first word because It will always ask me to enter a word even if the else statement terminates. I am using C language, not C++.
I got your problem. You problem is at this line.
while(choice!='E'||choice!='e')
You're using OR operation instead of AND operation. So, that line should be
while((choice != 'E') && (choise != 'e')).
Why your code failed when entering e or E:
If you entered e then,
while( `e` != `E` || `e` != `e`)
----------
^
returns true. so controller goes to the while loop.
same with E too.
How && works:
If you entered e then,
while( `e` != `E` && `e` != `e`)
----------
^
returns true and checks second condition
while( `e` != `E` || `e` != `e`)
---------- ---------
^ ^
returns true. returns false. Condition failed. Don't enter into while.
Edit: 2nd problem
In else block, in switch-case add this instruction:
scanf("%c",&choice);
ohterwise your loop executes continuously.
There seem to be verious issues with your program. I'll address the mixed scanf and gets input I've hinted at in my comment here.
When you want to add an entry, you type 'A'. Nothing happens. That's because the input is buffered and is not sent to the program until a new-line was received, i.e. until the user presses return. Which the user does, of course, because nothing happend when 'A' was pressed. The 'A' still sits in the buffer, however. Now you ask the user to provide a word, which is read from the bufer with gets, which reads input until the end of a line is found.
But yout input bufer looks like this:
A newline w o r d newline
The 'A' has been consumed by scanf, but the newline hasn't. The next line you read is an empty line.
I suggest that you write a little framework for your most typical cases: Picking an item from a menu by typing a single letter plus newline and readlin a line of input. This still won't be ideal, because the normal input from the terminal doesn't lend itself to fancy menus, but it's a start. You should look into ncurses or possibly the options in <conio.h> if you want to write pretty DOS-style menus.
Anyway, here's a suggestion that should get you an idea:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int read_key()
{
char buf[40];
char key;
if (fgets(buf, sizeof(buf), stdin) == NULL) return -1;
if (sscanf(buf, " %c", &key) == 0) return 0;
return key;
}
int read_line(char *buf, int max)
{
int len;
if (fgets(buf, max, stdin) == NULL) return -1;
len = strlen(buf);
if (len) buf[--len] = '\0';
return len;
}
int main()
{
char buf[40];
int key;
int len;
printf("\nW e l c o m e !\n\n");
for(;;) {
printf(" (L) Look\n");
printf(" (R) Register\n");
printf(" (Q) Quit\n");
printf("\n");
key = read_key();
switch (key) {
case 'l':
case 'L':
printf("You are in the school library in a maze of "
"twisted aisles, all different.");
break;
case 'r':
case 'R':
printf("Enter your name:\n");
len = read_line(buf, sizeof(buf));
if (len < 0) goto quit;
if (len) {
printf("Your name is %d letters (and spaces) long.\n", len);
}
break;
case 'q':
case 'Q':
case -1:
quit:
printf("Goodbye.\n");
exit(0);
break;
default:
printf("Oh, the letter '%c'. That's not on the menu.\n", key);
}
printf("\n");
}
}
I haven't looked too closely at the rest of your code, but it doesn't look too solid to me. For example, the showAll function is horrid with a never-ending while loop and an ad-hoc fread where you should probably be using fgets. It is also customary to keey a dictionary in memory and commit the changes to disk after the program has terminated.

Exercise6-4 programming in c

Right now I am learning to program in c by reading the book "Programming in C, 3rd edition" by Stephen Kockan.
Exercise6-4 in the book is really giving me a headache. In the book it says:
Write a program that acts as a simple "printing" calculator.
The program should allow the user to type in expressions of the form
number operator
The following operatros should be recognized by the program:
'+' '-' '*' '/' 'S' 'E'
The S operator tells the program to set the "accumulator" to the
typed-in number. The E operator tells the program that execution is to
end. The arithmetic operations are performed on the content of the
accumulator with the number that was keyed in acting as the seconcd
operand.
Here is a link,to how i figured it out too.
Unfortunately it's in Objective-C(but is still the same exercise!), and I don't understand
Objective-C syntax.
UPDATE
This is what I have made so far:
// "Printing" Calculator
#include <stdio.h>
int main(void)
{
char operator;
float value, result, accumulator;
printf("Begin Calculations...\n\n");
operator = '0';
while ( operator != 'E')
{
scanf("%f %c", &value, &operator);
switch(operator)
{
case 'S':
accumulator = value;
printf("The accumulator = %f", accumulator);
break;
case '+':
result = accumulator + value;
printf("%f + %f = %f", accumulator, value, result);
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
printf("Unknown operator");
break;
}
}
printf("Calculations terminated");
return 0;
}
I can't figure out how to use the scanf() function, and read both a value for an operation and a value for the accumulator. Because those two thing may not be the same.
Here is your C code.
#include <stdio.h>
#include <conio.h>
int main (void)
{
int loop;
float value,
acc = 0;
char o;
printf ("Simple Printing Calculator Program\n\n");
printf ("\nKEY: \n+ Add \n- Subtract \n* Multiply \n/ Divide\n");
printf ("S Set Accumulator \nE End Program\n\n");
printf ("Enter a number and an operator, then press enter\n\n");
printf ("Type in your expression: ");
for ( loop=0 ; loop>-1; ++loop)
{
{
scanf ("%f %c", &value, &o);
if ( o == '+' )
{
acc = acc + value; printf ("\n%.2f\n",acc);
}
else if ( o == '-' )
{
acc = acc - value; printf ("\n%.2f\n",acc);
}
else if ( o == '*' )
{
acc = acc * value; printf ("\n%.2f\n",acc);
}
else if ( o == 'S' )
{
acc = value; printf ("\n%.2f\n",acc);
}
else if ( o == 'E' )
{
printf ("\nFinal Value: %.2f\n\nGoodbye!",acc); loop = loop + 1000;
}
else if ( o == '/' )
if ( value == 0 )
{
loop = loop - loop -100;
printf ("\nDivision by zero.\n");
}
else
{
acc = acc / value; printf ("\n%.2f\n", acc);
}
else
{
loop = loop -loop-100;
printf ("\nUnknown operator.\n");
}
}
getch ();
return 0;
}

Resources