I'm practicing coding with arrays and I got a problem trying to test the input from the user.
This code lets the user input a binary sequence and do different operations with it.
I´ve accomplished most of it, my problem is that I cant find a way to limit the input of the user.
He should not be able to input more than 8 Bits and the input must only be 1s and 0s. I can imagine that I could use a for loop for this testing but I cant find a way to implement it so that it works properly.
I would be very thankful if someone could help me further.
Thanks in advance.
This is the code that I wrote:
#include <stdio.h>
#include <windows.h>
void bitCheck(int byte[], int position);
void bitSet(int byte[], int position);
void bitDelete(int byte[], int position);
void bitNegation(int byte[], int position);
int main( void )
{
int byte[7];
int position;
int selection = 0;
char c, i;
printf("%s\n======================\n\n", "Binary Operations");
printf("Byte in an 8-Bit sequence: ");
//My problem is in the code section below:
while (scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[7],&byte[6],&byte[5],&byte[4],&byte[3],&byte[2],&byte[1],&byte[0]) != 8 || byte[] != 0 || byte[] != 1){
printf("\nWrong input. Please write a valid 8-Bit sequence: ");
fflush(stdin);
}
while (selection!=5){
printf("\nAt which bit-position should the operation be made (7...0)?: ");
while (scanf("%d", &position) != 1 || position < 0 || position > 7){
printf("\nWrong input. Please write a valid position: ");
fflush(stdin);
}
printf("\n1: Bit check\n2: Bit set\n3: Bit delete\n4: Bit negation\n5: End\n\n");
while (scanf("%d", &selection) != 1 || selection < 1 || selection > 5){
printf("Wrong input. Please write a valid option: ");
fflush(stdin);
}
switch(selection){
case 1: bitCheck(byte, position);
break;
case 2: bitSet(byte, position);
break;
case 3: bitDelete(byte, position);
break;
case 4: bitNegation(byte, position);
break;
case 5: return 0;
}
}
getchar();
}
//Sorry for the german language in the code below, i think this code is not relevant for my question, but I still wanted to post it
void bitCheck (int byte[], int position){
if(byte[position]==1)
{
printf("\nDas Bit an der Position %d ist gesetzt.\n", position);
}
else if(byte[position]==0)
{
printf("\nDas Bit an der Position %d ist nicht gesetzt.\n",position);
}
}
void bitSet(int byte[], int position)
{
if(byte[position]==1)
{
byte[position]=0;
printf("\nNach der Bitoperation ergibt sich folgendes Bitmuster für das Byte: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
else if(byte[position]==0)
{
byte[position]=1;
printf("\nNach der Bitoperation ergibt sich folgendes Bitmuster für das Byte: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
}
void bitDelete(int byte[], int position)
{
if (byte[position]==1)
{
byte[position]=0;
printf("\nNach der Bitoperation ergibt sich folgendes Bitmuster für das Byte: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
else if (byte[position]==0)
{
printf("\nDas Bit ist schon auf 0 gesetzt!\n");
printf("\nDas Byte hat selbes Bitmuster wie davor: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
}
void bitNegation (int byte[], int position)
{
if (byte[position]==1)
{
byte[position]= 0;
printf("\nNach der Bitoperation ergibt sich folgendes Bitmuster für das Byte: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
else if (byte[position]==0)
{
byte[position]=1;
printf("\nNach der Bitoperation ergibt sich folgendes Bitmuster für das Byte: %d%d%d%d%d%d%d%d\n",byte[7],byte[6],byte[5],byte[4],byte[3],byte[2],byte[1],byte[0]);
}
}
Related
Ok, so I'm a computer science student (so I'm still learning) and I'm trying to program a drink maschine thingy. The thing is, it only executes the first if- block. I can't find my mistake and would really appreciate some help, so that I can fix the mistake and know what I did wrong.
I made some comments in the code, so it's better understandable for non German speakers, since the main text (which is mostly unimportant) is in german.
Here is the complete code for reverence
#include <stdlib.h>
#include <stdio.h>
void Fkt(int);
int main(void) {
int x; /*Not important in this part of code */
char G; /*The drink you choose will be G*/
float p; /* p = price */
printf("*** Getraenke Automat *** \n*W) Wasser (0.5 Euro)* \n*B) Bionade (1 Euro)*\n*O) Orangensaft (2 Euro)*\n***********************\n\nBitte ein Getränk auswaeheln "); /*Basically just asking what drink you want with the prices */
scanf("%c", &G); /* User picks drink*/
if ( G == 119 || 87) { /*This if block works perfectly fine */
printf("\n Bitte Zahlen Sie 0.5 Euro ");
scanf("%f", &p);
if ( p == 0.5) { /*If you pay the right amount of money */
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else { /*For the wrong amount of money*/
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
}
else if ( G == 66 || 98) { /* This one is stated as "Will never be executed */
printf("\n Bitte Zahlen Sie 1 Euro ");
scanf("%f", &p);
if ( p == 1) {
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else {
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
}
return 0;
}
void Fkt(int x){
printf("\n------------\n");
}
I tried to give every drink a different pice (Lemonade 1 Euro, Water 0.5 Cent) but no matter what input is given it always only gives me the price of the first drink.
I don't know if I made a small silly error or just did it completly wrong.
So here is my problem area:
if ( G == 119 || 87) { /*This if block works perfectly fine */
printf("\n Bitte Zahlen Sie 0.5 Euro ");
scanf("%f", &p);
if ( p == 0.5) { /*If you pay the right amount of money */
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else { /*For the wrong amount of money*/
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
}
else if ( G == 66 || 98) { /* This one is stated as "Will never be executed */
printf("\n Bitte Zahlen Sie 1 Euro ");
scanf("%f", &p);
if ( p == 1) {
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else {
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
I think you might want statements like if ( G == 66 || G == 98) instead of what you have. I don't think the code as written does what you think it does.
When you do G == 66 || 98 it will first evaluate G == 66 (which will evaluate to true or false) and then apply that value to 98 via the || operator, which will always return true (|| is usually applied to boolean values). It will not check whether G is 66 or 98...
The problem you have here is because you are saying
if ( G == 119 || 87)
Here, it tests if G is equal to 119, and if 87 is not 0.
The following code might help you understand how C works when using int as bool.
int a = 5;
if (a)
{
printf("Not zero\n");
} else {
printf("Zero\n");
}
a = 0;
if (a)
{
printf("Not zero\n");
} else {
printf("Zero\n");
}
The code above will print
Not zero
Zero
You should probably try
if ( G == 119 || G == 87) { /*This if block works perfectly fine */
printf("\n Bitte Zahlen Sie 0.5 Euro ");
scanf("%f", &p);
if ( p == 0.5) { /*If you pay the right amount of money */
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else { /*For the wrong amount of money*/
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
}
else if ( G == 66 || G == 98) { /* This one is stated as "Will never be executed */
printf("\n Bitte Zahlen Sie 1 Euro ");
scanf("%f", &p);
if ( p == 1) {
printf("\n Entnehmen Sie Ihr Getränk \n");
}
else {
printf("\nGeben Sie den richtigen Betrag ein!\n");
}
This is my current programm in which i take 3 different (or the same) values of N Natural Numbers and calculate their checksum, the usage of long datatype is a must as i also need to be able to calculate the checksum of values that exceed the MAX of int. I cant change the datatype. Now I also need to catch when the user enters a a non natural numbers e.g -23, 2.3 ... Ive made if statements that catch if a negative number and a number that exceeds the MAX of long is entered, the actual problem is that when i enter decimal numbers it skips my if conditions and prints out the printf functions but not any of the other functions, ive tried catching the decimal number with x % 1 !=0 which does not work because the actual value of x doesnt seem to be stored as a decimal but rather a whole number , ive confirmed this in various places in my programm by printing the value of x.
Im really new to C barely 2 weeks into studying and havent really grasped everything, but i really just cant seem to find the problem in my Programm.
I know my code looks like spaghetti code.
P.S Excuse my awful english
#include <stdio.h>
#include <stdlib.h>
int checksum(long q){
long countingVariable = 0;
while(q > 0)
{
countingVariable += q%10; // steht für sx = s + q%10
q/=10; // steht für q = q/10
}
return countingVariable;
}
int main(void) {
long x,y,z;
long long max_long = 2147483647;
printf("Bitte geben sie ihre erste Zahl ein:\n"); // enter first number
scanf("%ld",&x);
long sx = quersumme_1(x); // checksum of x first number
if ( x > 0 && x < max_long && x % 1 != 0){ // check if positive and natural number
printf("Bitte geben Sie ihre zweite Zahl ein:\n"); //enter second number
scanf("%ld",&y);
if (y > 0 && y < max_long){
long sy = quersumme_2(y); //checksum of y second number
printf("Bitte geben sie ihre dritte Zahl ein:\n");// enter third number
scanf("%ld",&z);
if (z > 0 && z < max_long){
long sz = quersumme_3(z); // checksum of z 3rd number
if (sx>sy && sx>sz && sy>=sz){
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
} else if (sx>sy && sx>z && sz>sy){
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
} else if (sy>sx && sy>sz && sx>=sz){
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
} else if (sy>sx && sy>sz && sz>sx){
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
} else if(sz>sx && sz>sy && sx>=sy){
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
} else if(sz>sx && sz>sy && sy>sx){
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
} else if (sx==sy && sx==sz && sy==sz){
printf("Die Quersumme s der Zahl %ld ist %ld\n",x,sx);
printf("Die Quersumme s der Zahl %ld ist %ld\n",y,sy);
printf("die Quersumme s der Zahl %ld ist %ld\n",z,sz);
}
// the big if tree is just a sorting "algorithm" it sorts the values of checksums
}if (z < 0){ //check for negative number z
printf("Falsche Eingabe: Minus Zahl"); //error
exit(0);
}if (z > max_long){ // cant exceed Max value of long
printf("Falsche Eingabe: Zahl overflowed long");// error
exit(0);
}
}if (y < 0){ //check for negative number y
printf("Falsche Eingabe: Minus Zahl"); // error
exit(0);
}if (abs(y) > max_long){ // cant ewxceed max value of long
printf("Falsche Eingabe: Zahl overflowed long"); /error
exit(0);
}
}if (x < 0){ //check for negative numbers
printf("Falsche Eingabe: Minus Zahl"); // error
printf("%ld",x);
exit(0);
}
if (x > max_long){ // cant exceed max of long
printf("Falsche Eingabe: Zahl overflowed long"); // error
exit(0);
}
return 0;
}
The best is to use fgets() read the line of user input into a string and then parse the string.
Let us say you are stuck with scanf() (too bad).
First, check return value
// scanf("%ld",&y);
if (scanf("%ld",&y) != 1) {
printf("Non-numeric input, end-of-file or input error");
exit(0);
}
Now read the next character
unsigned char ch;
if (scanf("%c",&ch) != 1) {
printf("Failed to read next character");
exit(0);
}
if (!isspace(ch)) {
printf("Unexpected character following a number %d %c\n", ch, ch);
exit(0);
}
Now check for range
if (y < min_long || y > max_long) {
printf("Out of range %ld\n", y);
exit(0);
}
Simplifications exist.
Again better to use fgets().
A robust, but unchecked, example:
#define LINE_SZ 100 // Max expected line size
char buf[LINE_SZ * 2]; // Let us read even up to 2x expected
if (fgets(buf, sizeof buf, stdin) == NULL) {
printf("Nothing read\n", y);
exit(EXIT_FAILURE);
}
errno = 0;
char *endptr;
long y = strtol(buf, &endptr, 0);
if (buffer == endptr) {
printf("Non-numeric input \"%s\"\n", buf);
exit(EXIT_FAILURE);
}
if (errno || y < long_min || long_max) {
printf("Input \"%s\" outside [%ld %ld] range\n", buf, long_min, long_max);
exit(EXIT_FAILURE);
}
// Skip trailing white-space
while (isspace((unsigned char)*endptr)) {
endptr++;
}
if (*endptr) {
printf("Trailing junk in \"%s\"\n", buf);
exit(EXIT_FAILURE);
}
printf("Success %ld\n", y);
If you cannot use fgets() to read a line into a string, try
char buf[100];
if (scanf(" %99[^\n]", buf) == 1) {
// OK, now process the string
A long type can not store a decimal value, and scanf will always try to match what the user entered to the type of value you told it to expect.
In your case, %ld means that if user enters a decimal number, scanf will ignore the '.' and everything after it, and only put digits before '.' in y.
There is one way to deal with this in C:
Read a string from the user and check the characters in it to make sure they are all digits (or that there is no decimal point or whatever else you need to check).
Then you can use atol to convert the string to long.
In any case, you should check the value scanf returns.
This usually is not taught in beginner classes, but scanf returns how many items from the user it matched to your expectations and stored in the variables you provided.
In your case it should return 1 if a valid integer was entered.
This method won't tell you if the user entered a decimal number or a word instead of a natural number, but you will know if the input was valid or not.
so i've written some example code and was wondering why i get a multiple of the same outputs
when i printf my result after having unwanted inputs.
does anybody has an idea?
#include <stdio.h>
int eingabe, ergebnis;
int quer(int result)
{
result = eingabe*eingabe;
return result;
}
int check(void)
{
if (eingabe > 10000)
{
printf("\nDie eingegebene Zahl ist zu groß!\n\n");
main();
}
else if (eingabe < 0)
{
printf("\nDie eingegebene Zahl ist zu klein!\n\n");
main();
}
}
int main()
{
printf("Bitte geben Sie eine Zahl von 0-10000 ein: ");
scanf("%d", &eingabe);
check();
ergebnis = quer(eingabe);
printf("%d² = %d\n", eingabe, ergebnis);
}
an output example would look like this:
Bitte geben Sie eine Zahl von 0-10000 ein: -3
Die eingegebene Zahl ist zu klein!
Bitte geben Sie eine Zahl von 0-10000 ein: 11111
Die eingegebene Zahl ist zu groß!
Bitte geben Sie eine Zahl von 0-10000 ein: 3
3² = 9
3² = 9
3² = 9
Recursively calling main is not a good idea (it’s forbidden by the standard IIRC). In your case, however, it seems to work like a normal function: when you call it yourself, its end does not end the program, but returns control instead. So when main calls check that calls main, that inner instance returns, check returns and the printf is executed again.
Since you have called main in your check function, it justs keeps on going back and forth endlessly. It is never advisable to call main function
Thank you for all your help and suggestions!
i've tried to rewrite some of my code to implement them.
alltough i have one last question how id be possible to ask for input again after the check failed..
#include <stdio.h>
int eingabe, ergebnis;
int quer(int result)
{
result = eingabe*eingabe;
return result;
}
int check(void)
{
if (eingabe > 10000)
{
printf("mache falsch\n");
return 0;
} else if (eingabe < 0)
{
printf("mache falsch\n");
return 0;
} else
{
printf("mache richtig\n");
return 1;
}
}
int main()
{
int checked;
printf("Bitte geben Sie eine Zahl von 0-10000 ein: ");
scanf("%d", &eingabe);
checked = check();
if (checked == 1) {
ergebnis = quer(eingabe);
printf("%d² = %d\n", eingabe, ergebnis);
} else if (checked == 0){
printf("Zahl nicht im Wertebereich!\n");
return 0;
}
}
so I declared a float named price and when I try to compile it I get a waring that it would be a double, can someone tell me why C think that this is a double ?
B3N2.c:37: warning: format specifies type 'float *' but the argument has type 'double' [-Wformat]
scanf("%f", la[i].preis);
int main(int argc, char *argv[]) {
struct Lager {
char artikel[200];
int anzahl;
float preis;
} la[200];
printf("Wilkommen bei Lagerverwaltung 97\n\n\nWas möchten sie tun ?\n");
int exit = 0;
int x,v;
int f = 1;
int i = 0;
char ques;
int end;
do {
printf("\n(1)Artikel hinzufügen\n(2)Artikel entnehmen.\n(3)Eintrag suchen.\n(4)Lager ausgeben.\n(5)Exit\n");
scanf("%x",&x);
switch (x) {
case 1://add
do {
printf("\nGebe den namen des Produkts an: ");
scanf("%s", la[i].artikel);
printf("\nAnzahl der verfügbaren Produkte: ");
scanf("%i", &la[i].anzahl);
printf("\ngib den preis des artikels an: ");
scanf("%f", la[i].preis);
printf("\n\nWeiteres Produkt hinzufügen ? (J/N)");
scanf("%s", &ques);
switch (ques) {
case 'J':
v++;
f++;
break;
case 'N':
end = 1;
v = 0;
break;
default:
printf("Falsche Eingabe\n");
break;
}
} while (end != 1);
if (v >= 2) {
printf("Produkt wurde Erfolgreich hinzugefügt\n\n");
}else {
printf("Produkte wurden Erfolgreich hinzugefügt\n\n");
}
break;
sorry for the dumb question but I tryed to fix it and now i'm totally Overwhelmed
scanf() needs a pointer to the space (that is, the variable) where the scanned value will be stored. But your call hands over the value of la[i].preis which is a float that is cast automatically into a double.
Change your code to give the address of la[i].preis to scanf() by using the & operator like this:
scanf("%f", &la[i].preis);
#include <stdio.h>
void aeins(){
int x;
unsigned int y;
double z;
printf("Geben sie einen ganze Zahl ein: ");
scanf("%d", &x);
printf("Geben sie eine natürliche Zahl ein: ");
scanf("%u", &y);
printf("Geben sie eine reelle Zahl ein: ");
scanf("%lf", &z);
printf("Die dritte Potenz von %d ist %d", x, x*x*x);
printf("Die dritte Potenz von %u ist %u", y, y*y*y);
printf("Die dritte Potenz von %lf ist %lf", z, z*z*z);
}
void azwei(){
printf("Geben sie einen Character ein: ");
char c = getchar();
printf("Das nachfolgende Zeichen lautet: %c und der ASCII-Wert ist: ", c+1, c+1);
}
int main (void){
int a;
int b = 1;
while(b){
printf("Welche Aufgabe soll gezeigt werden? ");
printf("\n(1) Aufgabe 1 \n(2) Aufgabe 2\n");
scanf("%d", &a);
switch(a){
case 1: aeins();
b = 0; break;
case 2: azwei();
b = 0; break;
default: printf("Falsche Eingabe!\n"); break;
}
}
}
This is my Program and this is my output:
Welche Aufgabe soll gezeigt werden?
(1) Aufgabe 1
(2) Aufgabe 2
2
Geben sie einen Character ein: Das nachfolgende Zeichen lautet: und der ASCII-Wert ist:
Process returned 0 (0x0) execution time : 2.172 s
Press any key to continue.
As you can see my program is ignoring the getchar command. I have tried it with a scanf command, but it won't work too. In the function aeins works everything. I would say I am a beginner to intermediate c programmer if this helps you.
scanf has the interesting property that it leaves the newline character which terminated input in the input buffer, so you need to consume that before proceeding to any other input.
Just add a getchar() call after your scanf("%d", &a); and you should be good.
You can fix issue by using scanf(" %c",&c); or you need to write 1 more getchar() to consume newline character left from scanf("%d", &a);