C program Do while doesnt work [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
A have a problem with my program. I dont know what im doing wrong but loop do while doesnt work. At and program should ask "If you want to run this program again, press T.Other key should close this program.
#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
#include <time.h>
int main()
{
int a;
int b;
int c;
int f;
int g;
int h;
int d = 0;
char e;
srand(time(0));
do {
printf("How many numbers do you want to show: ");
scanf_s("%i", &a);
printf("od: ");
scanf_s("%i", &b);
printf("do: ");
scanf_s("%i", &c);
h = c + 1;
f = b - h;
for (d; d < a; d++) {
printf("%i ", b + rand() % f);
}
printf("\n");
printf("Restart program? T- Yes");
scanf_s("%s", &e);
} while (e == 't');
_getch();
return 0;
}
Program works fine, but when i press T at the end. it will close. Im using Visual Studio 2015
Now my code is below:
do {
printf("How many numbers do u want: ");
scanf_s("%i", &a);
printf("od: ");
scanf_s("%i", &b);
printf("do: ");
scanf_s("%i", &c);
h = c + 1;
f = b - h;
//printf("%i %i %i\n", h, f);
for (d; d < a; d++) {
printf("%i ", b + rand() % f);
}
printf("\n");
printf("Restart? T- yes");
scanf_s("%c", &e);
} while (e == 't' || e == 'T');
_getch();
return 0;
}
But it still doesnt work. I cant enter any letter. When i press any key a windows is going to close

As others have pointed, this is because you're trying to get a "%s" and, therefore, you can't compare it to a character. Use "%c" instead, or use strcmp function to compare 2 char arrays.
By the way, be aware that scanf_s is a Microsoft only function. Not sure if visual studio is forcing you to use it, but the common usage of scanf wouldn't hurt, check it out:
scanf("%c", &e);

Do you press 'T'? because 'T' and 't' are not the same character. check the ascii table
Your program will continue while you press a 't' so with a 'T' or anything else it will stop.
ps: You may want to use "read(0, &e, 1);" or "scanf_s("%c", &e);" instead of "scanf_s("%s", &e);" (last line of do while), because you have a char and if you enter a string like "Mr T. says yes" it will overwrite your memory which is never good.As a reminder char is 1 byte in memory, with '&' you can access its place in memory, so it acts like a string but if you write more than 1 character it will just write in the following memory which isn't attributted to your program. it will probably do nothing but it can overwrite another of your variable or worse overwrite another program in your computer (hopefully not something important like a window's program or else!)
char and string basics

Related

what is the bug that is preventing this C code from determining the right answer? [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 months ago.
I'm new to C and I'm building a quiz game, every time you answer right your score gets higher, however there is a bug that i was not able to find which is even if you answer correctly the code will tell you that you are wrong and moves to the next question in the end you will always get a score of 0/3.
my question is what is the reason that is preventing my code from determining that the answer is right, why does it always go to the else statement which is wrong.
this is the code
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char questions[][100] = {
"\n1. what company was the first to create a foldable phone? ",
"\n2. what company was the first to create a foldable laptop? ",
"\n3. what company was the first to create a full electric car? "
};
char options[][100] = {
"\nA. apple, B. oppo, C. samsung, D. motorolla",
"\nA. Asus, B. MSI, C. Microsoft, D. Gygabyte",
"\nA. mazda, B. chevrollet, C. toyota, D. Tesla"
};
char answers[] = {'C', 'A', 'D'};
int score = 0;
char ans;
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%s", questions[i]);
printf("%s", options[i]);
printf("\n\nwhat is your answer? ");
scanf("%c", &ans);
scanf("%c");
ans = toupper(ans);
if (ans == answers[i])
{
score += 1;
printf("\nthat's right!");
printf("\nnext question\n");
}
else
{
printf("\nwrong!");
printf("\nnext question\n");
}
}
printf("\n\nthe correct answers are: ");
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%c ", answers[i]);
}
printf("\nyour score is: %d/3", score);
}
ans is the user guess.
if anyone have the solution for this i would really appreciate it.
thanks in advance.
ok , so you have only one problem in your code and a warning .
in these 2 lines :
scanf("%c", &ans);
scanf("%c");
when the user enter a char like a and press enter , the first scanf will get a successfully but the second scanf("%c"); is incorrect as you are telling the function to get a character from the input and store it but where ? , it gave me undefined behavior .
note that , in order to clear the buffer after reading one char , you can simply write instead of the above 2 lines , these lines :
scanf("%c", &ans);
fgets(dummy, sizeof(dummy), stdin);
where fgets(dummy, 20, stdin); will read any chars there in the buffer so as to clear it.
also there is a warning in this line ans = toupper(ans); as the warning in my compiler says :
Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined
as the function called toupper takes int and returns int but you are storing the result into a char , so either cast the result as ans = (char)toupper(ans); or you can use _toupper which takes char and returns char like ans = _toupper(ans);
and this is the full code with these only 2 edits :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char questions[][100] = {"\n1. what company was the first to create a foldable phone? ",
"\n2. what company was the first to create a foldable laptop? ",
"\n3. what company was the first to create a full electric car? "};
char options[][100] = {"\nA. apple, B. oppo, C. samsung, D. motorolla",
"\nA. Asus, B. MSI, C. Microsoft, D. Gygabyte",
"\nA. mazda, B. chevrollet, C. toyota, D. Tesla"};
char answers[] = {'C', 'A', 'D'};
int score = 0;
char ans, dummy[20];
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%s", questions[i]);
printf("%s", options[i]);
printf("\n\nwhat is your answer? ");
scanf("%c", &ans);
fgets(dummy, sizeof(dummy), stdin);
ans = _toupper(ans);
if (ans == answers[i])
{
score += 1;
printf("\nthat's right!");
printf("\nnext question\n");
}
else
{
printf("\nwrong!");
printf("\nnext question\n");
}
}
printf("\n\nthe correct answers are: ");
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%c ", answers[i]);
}
printf("\nyour score is: %d/3", score);
}
and this is the output :
1. what company was the first to create a foldable phone?
A. apple, B. oppo, C. samsung, D. motorolla
what is your answer?c
that's right!
next question
2. what company was the first to create a foldable laptop?
A. Asus, B. MSI, C. Microsoft, D. Gygabyte
what is your answer?a
that's right!
next question
3. what company was the first to create a full electric car?
A. mazda, B. chevrollet, C. toyota, D. Tesla
what is your answer?d
that's right!
next question
the correct answers are: C A D
your score is: 3/3
Process finished with exit code 0

If we want to call switch statement more than 1 in C Program, what should I do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For example, if I want to call switch statement in for loop, I got an error.How can I correct this issue?If I want to move my switch statement outer part in determined condition which is to be using more than calling switch statement. Thanks in advance.
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 50
int i = 0;
int main() {
char usertxt[SIZE], myoperator[SIZE];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf_s("%d", &x);
for (i = 0; i < x; i++) {
scanf_s(" %c", &myoperator[i], 1);
switch (myoperator[i]) {
case '+':printf("Addition operation\n");
printf(" Enter your number: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '-':printf("Subtraction operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '*':printf("Multiplication operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '/':printf("Division operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
default :if (myoperator[i] == '\0') {
break;
};
}
}
}
As #Gerhardh said, welcome to SO.
But I really think that the logic behind your code isn't good enough.
I take some time to understand your goal and I make a new clearer version.
While testing and understanding your code, I've encountered the following problems:
Implicit declaration of function 'scanf_s' is invalid in C99
Declarations of global variables as counters and their usage inside the loop were the main reason why your code doesn't work as expected.
The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value. You used it like it returns a char or even a string.
Switch statement is useless if you have to do always the same operations.
Char reading doesn't work correctly.
I'm gonna attach here the updated code. Hope that it could be helpful and that actually it has the same "goal" that your code has.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 500
#define nOperator 4
int main() {
char usertxt[SIZE], myoperator[nOperator];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int nOperations;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf("%d", &x);
printf("How many operations would you like to try? ");
scanf("%d", &nOperations);
for (int i = 0; i < nOperations; i++) {
fseek(stdin, 0, SEEK_END);
printf("\n\nEnter operation #%d: ", i + 1);
myoperator[i] = getchar();
for (int j = 0; j < x; j++) {
printf("Enter number #%d: ", j + 1);
scanf("%d", &myarray[j]);
}
int k = 0;
for (int m = 0; m < x; m++) {
if (m == x - 1) {
usertxt[k] = myarray[m];
printf("%d", myarray[m]);
} else {
usertxt[k] = myarray[m];
usertxt[k + 1] = myoperator[i];
printf("%d%c", myarray[m], myoperator[i]);
}
k++;
}
printf("\n\n");
}
}
As you can see, I tried to stay as much as next to your code idea and implementation.
For instance, I've not deleted the initial pragma and define. Probably you are going to use them later.
I've used fseek(...) as suggested here:
How to clear input buffer in C?
in order to read correctly char and integers together.
First thing first, it reads the numbers that you want to use and the number of operations that you want to do. After that, it takes the numbers associated with a certain operation, and at the end, it prints the expression as you are doing in your own code.
If you want to add the result, you just need a little edit in the code to sum all the numbers in the array or counting them while reading from input.
Variable Counters Description:
i is for 'myoperator' array
k is for 'usertxt' array
m is for 'myarray' array
Next steps:
Add the result variable to display the result of the operation
Use dynamic memory
Note that:
fseek(...) works on some systems; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).
If you need that it has to be portable, then check the link that I've placed before.
Hope that it was helpful.
Cheers,
Denny

C - What is wrong with this code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I made a program which takes a user to input number, if user inputed number less than 0 or greater than 100, then program returns to main function.
Here is my code:
#include <stdio.h>
int main(){
int a; scanf("%d", &a);
if(a > 100 || a < 0) {
printf("Going back to program.");
return main();
} else {
printf("Your number: %d\n", a);
}
}
But this code doesn't take a input and it just prints "Your number: 0".
So, what is wrong with this code?
Using recursion here (calling main again from main) is overly complicated and useless.
You want this:
#include <stdio.h>
int main()
{
int a;
do
{
scanf("%d", &a);
} while (a > 100 || a < 0); // simply repeat scan if a is out of bounds
printf("Your number: %d\n", a);
}
This is basic C knowledge. You probbaly should start reading your C textbook.
Your code is not good... A better way of doing it would be to use a loop
Better Solution
int main(){
int a;
do {
scanf("%d", &a);
} while(a > 100 || a < 0);
printf("Your number: %d\n", a);
return 0;
}
Your working solution
int main(){
int a;
scanf("%d", &a);
if(a > 100 || a < 0) {
printf("Recursion");//You are not going back you go further in depth (Recursion)
return main();
} else {
printf("Your number: %d\n", a);
return 0;//You need to return in if and in else
}
}
This is basic knowledge about programming (with c). I think you are a beginner so maybe you want to start with an Tutorial?
There is nothing wrong with your code, it should work.
scanf() reads from stdin. Depending on how and where your program runs stdin can have different meanings.
On tutorialspoint.com, you have to supply data to stdin before running your program by using the "Stdin" tab.

Why does variable store different value than what user inputs? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having a problem setting a variable entered by the user. I entered something in and it stores another value. Pretty frustrating. So any guidance would be great.
Be advised, there are quite a few printf(), as I was trying to pinpoint the problem. Also I am still trying to get a hold of C.
#include <stdio.h>
int vehicletype, in, out; // User Entered Info
int vehicleID[5000];
float vehicleCharge[5000];
int i;
// Variables for Main Function
int q; // Loop Control
float z;
int main (){
for(q = 1; q != 1518944; q++) {
printf("Enter your position in the parking queue: ");
// Take the queue entered by the user and assign it to i
scanf("%d\n", &i);
// Take the user input(which is being held in the variable i) and place it into the 'i'
//position of the ID array
vehicleID[q] = i;
printf("Enter the time(past 0600) you wish to start parking: \n");
//take the time and pass it to the time function to determine roundup
scanf("%d\n", &in);
printf("Enter the time(before 2200) you wish to leave: \n");
scanf("%d\n", &out);
printf("Time in: %d\nTime out: %d\n", in, out);
}
return 0;
}
#M.M I should be able to enter 0617 into the "in" variable and 1547 for the "out" (I use this later to find out how much they parked) but the output I get when checking the variables by printing "in" and "out" is 1 and 399 respectively.
Here is some more or less working code. I don't understand the 1518944 limit, but the code takes steps to ensure that regardless of how many entries you make, the code won't write out of bounds of the array vehicleID. It also checks some numbers for validity, and echoes its inputs. The leading newlines on some of the outputs makes the output appear semi-sane when the data is written via another program (a random number generator was what I used to generate numbers 1-5000 and two times 0600-2200).
#include <stdio.h>
static int vehicleID[5000];
int main(void)
{
for (int q = 1; q != 1518944; q++)
{
int in, out;
int i;
printf("\nEnter your position in the parking queue: ");
if (scanf("%d", &i) != 1)
break;
vehicleID[q % 5000] = i;
printf("Enter the time (past 0600) you wish to start parking: ");
if (scanf("%d", &in) != 1)
break;
printf("Enter the time (before 2200) you wish to leave: ");
if (scanf("%d", &out) != 1)
break;
if (in < 600 || in > 2200 || out < 600 || out > 2200 || in >= out)
printf("Invalid times (in %.4d, out %.4d)\n", in, out);
else
printf("\nPosition: %d; Time in: %.4d; Time out: %.4d\n", i, in, out);
}
putchar('\n');
return 0;
}
Note that inputs are checked, and echoed. Checking is a crucial programming technique; printing (echoing) is a basic debugging technique.

What's the error in this program code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried using the ASCII code too by replacing %d with %c in `scanf() code. but then it displays - Add=5 (If I put the input 5 & 6 with 65 ASCII code)
#include <stdio.h>
#include <conio.h>
void main()
{
int num1,num2,res;
char ch;
printf("Enter two numbers");
scanf("%d%d",&num1,&num2);
printf("Enter the operator from the following\n\nA for +\nB for -\nC for*\nD for /\n");
scanf("%c",&ch);
if(ch=='A')
{
res=num1+num2;
printf("Add=%d",res);
}
else if(ch=='B')
{
res=num1-num2;
printf("Sub=%d",res);
}
else if(ch=='C')
{
res=num1*num2;
printf("Mul=%d",res);
}
else if(ch=='D')
{
res=num1/num2;
printf("Div=%d",res);
}
else
{
printf("Invalid Operator");
}
getch();
}
The output:
Any help?
You are facing, sadly, the same problem faced by every beginning C programmer ever: scanf sucks. When you called
scanf("%d%d",&num1,&num2);
it correctly read the two numbers that you typed. But after you typed the two numbers, you probably hit RETURN. And the first call to scanf did not read that return character. So it's still sitting there in the input buffer, and when you later call scanf("%c",&ch), it's actually the newline character that gets read, not the A or B that you wanted to read.
Without changing your program at all, you can try typing something like
12 34A
in response to the first prompt. The first scanf won't read it, so now it will be sitting there in the input buffer waiting for your second call to scanf to find it.
That's a workaround, not a fix. To fix it, you could do what #Ediac suggested in his answer.
(A better fix would probably be not to use scanf at all, but unfortunately that involves learning more about I/O than your book or instructor probably wanted to get into right at first.)
I'd rather write a more useful and correct version of this code
#include <stdio.h>
int main() {
int n1, n2, ans;
char op;
scanf("%d %c %d", &n1, &op, &n2);
switch (op) {
case '+':
ans = n1 + n2;
break;
case '-':
ans = n1 - n2;
break;
case '*':
ans = n1 * n2;
break;
case '/':
if (n2) {
ans = n1 / n2;
break;
}
default:
fprintf(stderr, "Invalid Input\n");
return 1;
}
printf("%d", ans);
return 0;
}
Input
1 + 2
4-3
Output
3
1
See http://ideone.com/y2nnWF demo.

Resources