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

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.

Related

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

Take user input and continue to use it's variable throughout [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 5 years ago.
Improve this question
Not doing anything special. Just taking a user's input between 1 - 500, and then printing the number using for loop for each iteration. It crashes at the for loop. It does not print anything at all.
#include <stdio.h>
int forCounter() {
int num;
int count = 0;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
int i = num;
for (i; count <= i; count++) {
printf(count);
}
getchar();
return 0;
}
I take first input applied to 'num' and check if it's above or below allowed amount with the while loop.
When that's done it leaves and should start the for loop with i taking over for num. I tried using num in the place of i but it didn't work so I tried using a separate variable to see if it'd work.
I get two warnings seen in the image providedTwo warnings
You have to specify the format of output in printf.
int printf(const char *format, ...)
Your code:
#include <stdio.h>
int forCounter(void) {
int num;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
for (int i = 1; i <= num; i++) {
// printf(count); --> Bad
printf("Value = %d\n", i);
}
getchar(); // this will return immediately
return 0;
}

I have to find two smallest numbers without arrays [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 5 years ago.
Improve this question
So basicly I have this assignement in C, I have to input numbers until I enter 0, and after I enter 0 I have to print 1st and 2nd min number from all that numbers and I can't use arrays. I get that I have to use do-while loop for input but I can't figure out how to find two smallest from all of them. I think that thing can be done with if loops but don't know how to make it as I have only one variable to enter numbers into it (int a). And in input I have error when I enter 0 I'm able to enter one more number before program quits.
#include <stdio.h>
int main() {
int a;
do {
printf("Enter numbers: ");
scanf("%d\n", &a);
//what to do here
}while(a != 0);
You need to add 2 variables to hold the smallest values detected so far. Like
int smallest = INT_MAX;
int second_smallest = INT_MAX;
Then in the loop you need to test if the new input value is smaller than the values stored so far. Something like:
if (a <= smallest)
{
second_smallest = smallest;
smallest = a;
}
else if (a < second_smallest)
{
second_smallest = a;
}
You can use two variables to do what you need
#include <stdio.h>
#include <limits.h>
int main(void)
{
int a = INT_MAX;
int min_1 = INT_MAX;
int min_2 = INT_MAX;
int valid;
do
{
if (a < min_1)
{
min_2 = min_1;
min_1 = a;
}
else if (a < min_2)
{
min_2 = a;
}
printf("Enter numbers: ");
valid = scanf("%d", &a);
}
while ((a != 0) && (valid == 1));
if (valid == 1)
{
printf("Minimum numbers entered are: %d %d\n", min_1, min_2);
}
else
{
fprintf(stderr, "Error in data input\n");
}
}
So:
use limits.h defines to init min variables to the highest value for int type INT_MAX.
for each loop you must test if entered number is a minimum
you must check that user input is valid: check scanf return value.
remove \n in the format string of scanf.

Infinite loop in C, what is wrong? [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 8 years ago.
Improve this question
I am having problems with the following code in different methods.
When i run my code and enter 2 as my parameter, i get an infinite loop of zero's and ones.
I'm not sure what is wrong with that section.
Any help would be great. Thank you!
/*global variables*/
int CPI[];
int Count[];
Whenever i choose 1 as my parameter, i enter 3 as my instruction classes however i am unable to input the CPI of class 3 or even the instruction count of class 3. Once i input the CPI and instruction count of class 2 it ends.
void SelectOne(){
tot = 0;
printf("\n Enter the number of instruction classes: ");
scanf("%d", &n);
printf("\n Enter the frequency of the machine (MHz): ");
scanf("%d", &f);
int CPI[n];
int Count[n];
int a;
for(a = 1; a < n; a++){
/*printf("%d",n);*/
printf(" Enter CPI of class %d : ", a);
scanf("%d", &CPI[a-1]);
printf(" Enter instruction count of class %d : ", a);
scanf("%d", &Count[a-1]);
tot =+ Count[a-1];
}
}
This is the method in which i get an infinite loop of 0's and 1's.
void SelectTwo(){
printf("\n ---------------------------");
printf("\n +Class/t + CPI/t +Count +");
int a;
for(a = 1; a <= n; a++){
printf("\n %d\t + %d\t + %d ", a, CPI[a-1], Count[a-1]);
}
}
I believe my problem is in main but i'm not sure of how to fix this.
int main(){
int sel = 1;
while(sel != 4){
printf("\n 1) Enter Parameters ");
printf("\n 2) Print table of parameters ");
printf("\n 3) Print table of performance ");
printf("\n 4) Quit");
printf("\n \n Enter Selection: ");
scanf("%d", &sel);
if(sel == 1){
SelectOne();
}
if(sel == 2){
SelectTwo();
}
if(sel == 3){
SelectThree();
}
else{
printf("quit");
}
}
}
"Whenever i choose 1 as my parameter, i enter 3 as my instruction classes however i am unable to input the CPI of class 3 or even the instruction count of class 3. Once i input the CPI and instruction count of class 2 it ends."
This is because you tell it to. Here:
for(a = 1; a < n; a++){
if you enter 3, then the loop runs once when a == 1, a second time when a == 2, and then quits, because a < 3 is no longer true. You want this:
for( a = 0; a < n; a++ ){ /* Change a = 1 to a = 0 */
printf(" Enter CPI of class %d : ", a + 1);
scanf("%d", &CPI[a]); /* Change [a-1] to [a] */
printf(" Enter instruction count of class %d : ", a + 1);
scanf("%d", &Count[a]); /* Change [a-1] to [a] */
tot += Count[a]; /* Change =+ to += and [a-1] to [a] */
}
Your code has lots of other problems, though, including the fact that the global variables CPI and Count that SelectTwo() appear to be using are not the same ones that SelectOne() is writing to, because in SelectOne() you create local variables of the same name which hide them.
EDIT: You edited your question to show the definitions of your global arrays:
int CPI[];
int Count[];
What this is actually doing is declaring an incomplete type, because you're not providing a size. Once you get to the end of the translation unit, if the array still has an incomplete type, then it's assumed to have one element, which is here set to zero on program startup. So you're effectively creating one-element arrays, so attempting to loop over more than one element in SelectTwo() is just undefined and nonsensical behavior.
As mentioned, the CPI and Count that SelectOne() is using are not the same ones that you are defining globally, so SelectTwo() is not reading from what SelectOne() is writing to.
If you want to use global arrays like this, you have to provide a size, e.g.
int CPI[3];
int Count[3];
If you don't want to provide a size (for instance, because here you want the user to choose the size), then you'll have to either use malloc() or define a variable length array within a function and pass it to the functions that need it.

Largest value in array [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 8 years ago.
Improve this question
I've been asked to write a program that accepts a list of numbers until a non-numeric is encountered (up to 30 numbers), putting the numbers into an array, and keeping track of how many numbers were inserted. Then it should scan through the array to find the largest number, and print the largest.
This is what I've come up with:
#include<stdio.h>
int main()
{
const int INPUT = 30 ;
int size [INPUT];
int i, big;
printf("Type integer numbers, followed by q to quit: ");
while (scanf("%d", &size[INPUT]) != 'q')
{
for(i=0;i<size;i++)
scanf("%d",&INPUT[i]);
big = INPUT[0];
for(i=1;i<size;i++)
{
if(big<INPUT[i])
big=INPUT[i];
}
printf("The largest number is %d",big);
return 0;
}
Besides the problems, I listed in the comments. You seems to be comfused by the varaible names~ Anyway, I made some code for you.
#include<stdio.h>
int main()
{
const int MAX_INPUT = 30 ;
int input[MAX_INPUT];
int size=0, big;
printf("Type integer numbers, followed by q to quit: ");
while(size < MAX_INPUT){
if(scanf("%d", &input[size]) != 1){
break;
}
++size;
}
if(size ==0){
return 0;
}
big = input[size-1];
while( size-- > 0)
{
if(big<input[size]){
big=input[size];
}
}
printf("The largest number is %d\n",big);
return 0;
}
Tested with GCC 4.1.2 and Linux.
Return value of scanf:
Upon successful completion, these functions return the
number of successfully matched and assigned input items
further, you are mixing the size and input, you actually want the size to be a constant and input to be an array:
const int SIZE = 30 ;
int input[SIZE];
So the while loop should look like:
while (scanf("%d", &input[some_index]) == 1)
and of course this is wrong:
scanf("%d",&INPUT[i]); // should be ==> &input[i]

Resources