Nested If statement Ignoring scanf function - if-statement

I've made a program where the user inputs a x coordinate and a y coordinate, If the user inputs a letter I want the input to be repeated until a valid input has been inputed. After 3 attempts the program will end. However every time I run the program and input a test character the program skips the scanf function and doesn't test the nested if loops, I've tried the adding a space in the scanf function but That doesn't seem to work at all. Would appreciate some help thank you :)
Code:
printf("Insert first vector:\n");
vector1 = scanf(" %f %f",&x1,&y1);
printf("x1 %f y1 %f \n",x1,y1);
if(vector1 == 0)
{
printf("Invalid input\n");
printf("Insert first vector; \n");
vector2 = scanf(" %f %f",&x1,&y1);
if(vector2 == 0)
{
printf("Invalid input\n");
printf("Insert first vector; \n");
vector3 = scanf(" %f %f",&x1,&y1);
if(vector3 == 0)
{
printf("Invalid input \n");
x1=WRONG;

I'm assuming that you're using C Language.
int count = 1;
do {
printf("Insert First Vector: ");
fflush(stdin);
vector1 = scanf("%f %f", &x1, &y1);
count++;
} while (vector == 0 && count <= 3);
Try using above code.
I'm using do while loop just for sake of simplicity.

Related

Check if the input is a whole number in C++ in simple way using isdigit

This is what I have tried
It would always act as false no matter the input
How could I do it right in a simple way if possible and why doesn't it work?
I am trying to create a condition that would ask if the scanned user input is one of the numbers and if not it asks them to only write one of the shown numbers and shows what the options are.
void konc()
{
exit (0);
}
void scan()
{
int ch = 0;
printf("0 - \n");
printf("1 - \n");
printf("2 - \n");
printf("3 - \n");
printf("4 - \n");
printf("5 - \n");
printf("6 - \n");
printf("7 - \n");
scanf("%d", &ch);
while (isdigit(int(ch)) == false || ch < 0 || ch > 7){
printf("Must be one of the numbers\n");
fflush(stdin);
scan();
}
if (ch == 0){
konc();
}
printf("%d", ch);
scan();
}
int main()
{
scan();
return 0;
}
The problem is in the checking logic.
The number 0 is not the same thing as the character '0' (which is mapped to a value of 48).
Change the 0 to '0'. (and 7 also)
You have a few issues:
int ch = 0;
...
scanf("%d", ch);
scanf needs to be given a pointer to the data it's reading into, so this should be scanf("%d, &ch);
while (isdigit(int(ch)) == false || ch < 0 || ch > 7){
ch is already an int, so using isdigit doesn't make sense. It's already a number. Just check the range (while (ch < 0 || ch > 7) {)
fflush(stdin);
Using fflush on an input stream is undefined behavior. Get rid of this.
Instead of calling scan recursively, you should use a loop to jump back to the top:
int number;
while(1) {
printf("0 - \n");
printf("1 - \n");
printf("2 - \n");
printf("3 - \n");
printf("4 - \n");
printf("5 - \n");
printf("6 - \n");
printf("7 - \n");
scanf("%d", &number);
if(number < 0 || number > 7) {
printf("Must be one of the numbers\n");
continue; // Go back to the top of the loop
}
break;
}
// Now number is between 0 and 7
your logic is wrong. Make a loop which will continue until the user chooses a right number.
#include <conio.h>
#include <stdio.h>
int main(void)
{
scan();
}
void scan()
{
printf("Choose any of the following numbers:\n");
do
{
printf("0 - \n");
printf("1 - \n");
printf("2 - \n");
printf("3 - \n");
printf("4 - \n");
printf("5 - \n");
printf("6 - \n");
printf("7 - \n");
char ch; // now it is not undefined
scanf("%c",&ch);
fflush(stdin);
if(ch<48||ch>55) //ascii of '0' is 48 and ascii of '7' is 55.
printf("Must be one of the numbers\n");
else
break;
}while(1);
}
I have tested it.It will surely work.Also no need of isDigit()

Implicit declaration of printf

I'm getting implicit declaration error. Please help. I don't know how to explain it in terms of words, I'd appreciate it very much if you could help me with error. It's my assignment at school and I want to resolve the issue. Please help.
#include<stdio.h>
int printmenu(int *size_of_char);
int get_char(int **size_of_char);
int main() {
int choice = 0, size_of_char;
while (choice == 0) {
printf("Enter the size of the array: ");
scanf("%d", &size_of_char);
if (size_of_char <= 0) {
printf("Invalid input\n");
}
else {choice = printmenu(&size_of_char);
}
}
return 0;
}
int printmenu(int *size_of_char) {
int x;
printf("Menu\n\n");
printf("0. Input characters\n");
printf("1. Shift Elements to Right\n");
printf("2. Combinations of 2 digits\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &x);
if (x == 0) {
get_char(&size_of_char);
}
}
int get_char(int **size_of_char) {
char string[**size_of_char];
for(int i = 0; i < **size_of_char; i++){
printf("Enter value: %c ", i+1);
scanf("%c", &string[i]);
for(int i = 0; i < **size_of_char; i++){
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
//printf("Your grade in subject %d is %f.\n", i+1, *(grades + i));
}
}
}
Thanks
You've correctly included the header which declares printf in the example that you show.
There are other bugs however:
char string[**size_of_char];
This is ill-formed. The size of an array must be a compile time constant. That expression isn't.
int printmenu(int *size_of_char)
printmenu is declared to return int, but there is no return statement. The behaviour of the program is undefined.
// int **size_of_char
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
You're trying to print a int* with a wrong format specifier. The behaviour of the program is undefined.

Why does EOF not terminate during my scanf while loop?

I just started learning C++ and am trying to learn how to use scanf and printf for faster input and output. Here is the code I'm currently working on:
#include <stdio.h>
using namespace std;
int main() {
int time, record;
double down, loan;
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF) {
double value = down + loan;
double owed = loan;
double payment = owed/time;
// current simulated month and depreciation
int rday, c = 0;
double temp, dep;
bool found = false;
// finds value and owed after records
while (!found && record > 0) {
scanf("%d %lf", &rday, &temp);
// adjusts value and owed to day before listed on record
while (!found && c <= rday) {
if (c == rday) {
dep = temp;
}
value *= 1 - dep;
if (c > 0) {
owed -= payment;
}
c++;
// determines if found date
if (owed < value) {
found = true;
}
}
record--;
}
// finds point where owed < value
while (!found && value < owed) {
value *= 1 - dep;
owed -= payment;
c++;
}
if (c - 1 == 1) {
printf("%d month\n", c - 1);
}
else {
printf("%d months\n", c - 1);
}
}
return 0;
}
When I run this on Code::Blocks, it prints the correct answers, but the outermost while loop doesn't terminate even when I enter CTRL+Z (I am using Windows). Here is my input:
30 500.0 15000.0 3
0 .10
1 .03
3 .002
12 500.0 9999.99 2
0 .05
2 .1
60 2400.0 30000.0 3
0 .2
1 .05
12 .025
-99 0 17000 1
Here is an image of the what happens:
Error
I've tried changing the loop condition to scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4, but the same problem happens. Could someone please explain what the issue with my code is?
In the line
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF)
you expect 4 variables to be read into when the read is successful. When scanf is able to successfully extract the data from stdin for all the arguments, it will return 4. Change the check to use that number.
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4)
It's because scanf never returns EOF, so the termination condition is never satisfied.
Thanks for the suggestions and answers, everyone! I figured out the bug. Kind of embarrassing, but it turns out the issue was with the last line of input.

Assigning values to an array after malloc causes crash

I got a little assignment to do with C, but I can't seam to fill up an array that I allocated memory to. The code is like so..
#include<stdio.h>
#include<stdlib.h>
int main(){
int *x, *y, n, m, i;
printf("Enter lenght of arrays x and y (separated by space): ");
scanf("%d%d", &n, &m); fflush(stdin);
if (x = (int*)malloc(sizeof(int) * n) == NULL){
fprintf(stderr, "Error!\n");
exit(1);
}
if (y = (int*)malloc(sizeof(int) * m) == NULL){
fprintf(stderr, "Error!\n");
exit(1);
}
printf("Enter %d values for X array (separated by space) ", n);
for (i = 0; i < n; i++)
scanf("%d", x + i);
fflush(stdin);
printf("Enter %d values for Y array (separated by space): ", m);
for (i = 0; i < m; i++)
scanf("%d", y + i);
} //the two for's were originally in a function, I tried using the code like this as well
return 0;
}
I also tried running scanf("%d", x[i]); but nothing works. Every time I hit Enter after typing in the array for X the program crashes. By the way, originally no fflush(stdin) was there originally, I added them because I thought that the input took \0 as one of the values and that created errors.
Thank you for reading! :)
The code has a bunch of misplaced braces and parentheses, especially in the if statements. You have to wrap the assignments in parenthesis before doing the comparison, else they're misassigned. Try this, it compiled and worked for me:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *x, *y, n, m, i;
printf("Enter lenght of arrays x and y (separated by space): ");
scanf("%d%d", &n, &m);
if ((x = (int*)malloc(sizeof(int) * n)) == NULL){
fprintf(stderr, "Error!\n");
exit(1);
}
if ((y = (int*)malloc(sizeof(int) * m)) == NULL){
fprintf(stderr, "Error!\n");
exit(1);
}
printf("Enter %d values for X array (separated by space) ", n);
for (i = 0; i < n; i++)
scanf("%d", x + i);
printf("Enter %d values for Y array (separated by space): ", m);
for (i = 0; i < m; i++)
scanf("%d", y + i);
//the two for's were originally in a function, I tried using the code like this as well
return 0;
}
And like everyone else says, don't use fflush(stdin)
The use of fflush(stdin) is probably causing the crash, since it's undefined behavior in standard C.
Take a look at this answer what is the use of fflush(stdin) in c programming
I tried to compile the programm with Visual Studio 2013 and got 2 errors at the lines with malloc:
error C2440: '=' : cannot convert from 'bool' to 'int *'
After i fixed both lines by
if ((x = (int*)malloc(sizeof(int) * n)) == NULL){
or
if (x = (int*)malloc(sizeof(int) * n)){
the program runs without any problems.
I don't understand why you could compile the code, but it does the following:
compare (int*)malloc(sizeof(int) * n) == NULL result is false
and now set y = false and y does not point to the allocated array.

Complete Beginner: Null pointer issue?

I have looking all over forums to try and understand this issue. The reasons I cannot fully understand the issue and why I cannot find a solution is because I am fairly new with C++ and I do not understand the error message.
This is my code in C++ that finds the number of possibilities from permutation or combination formulas. Every I try and compile and run, I get messages that say:
First-chance exception at 0x6a8613af (msvcr100d.dll) in
Combinations_Permutations.exe: 0xC0000005: Access violation reading
location 0x00000005. Unhandled exception at 0x6a8613af (msvcr100d.dll)
in Combinations_Permutations.exe: 0xC0000005: Access violation reading
location 0x00000005.
I've learned on many other forums that the "access violation reading location 0x00..." could definitely indicate null pointer. But I cannot see where I encounter such a null issue. Maybe my variables are being accessed globally, where they are not YET initialized?
Here is my code, I have been at it for a while... like I said I'm fairly new. So please inform me of my mistake(s). Thank you.
My code:
#include <iostream>
#include "conio.h";
using namespace std;
int run_combination(int n, int r);
int run_permutation(int n, int r);
int solve_factorial(int f);
int f_value = 1; //factorial value used recursively
int n_input, r_input;
char choice;
char order;
void main(){
//if user types choice as 'q', while loop ends
while(choice != 'q'){
printf("How many values? (1-9) \n");
printf("User: ");
cin >> n_input;//user input for variable n
printf("n_input: %i", n_input);
printf("\nHow many will be chosen at a time out of those values? (1-9)\n");
printf("User: ");
cin >> r_input; //user input for variable r
printf("\nDoes order matter? (y/n)\n");
printf("User: ");
cin >> order; //'y' if order is taken into consideration(permutation)
//'n' if order it NOT taken into consideration(combination)
int solution = 0; //temporary variable that represents the solution after running
//n and r through the permutation or combination formula
//if user input values for n and r are in between 1 and 9, then run
//combination or permutation
if (n_input <= 9 && n_input >= 1 && r_input <= 9 && r_input >= 1){
if (order == 'y')
solution = run_permutation(n_input, r_input);
else if (order == 'n')
solution = run_combination(n_input, r_input);
else
printf("\nError. Please type 'y' or 'n' to determine if order matters.\n");
//if n < r, run_permutation or run_combination returns 0
if (solution == 0){
printf("Error! You can't choose %i values at a time if there \n",
"are only %i total values. Type in new values next loop \n.", r_input, n_input);
}
else
printf("Number of possibilities: %s", solution);
}
else{ //else error message if numbers are out of range...
printf("Next loop, type in values that range from 1 to 9.\n");
}
//option 'q' to quit out of loop
printf("Type 'q' to quit or enter any key to continue.\n");
printf("User: ");
cin >> choice;
}
_getch();
}
/*
Returns solved combination of parameters n and r
Takes the form: n! / r!(n-r)!
*/
int run_combination(int n, int r){
if (n < r) //solution is impossible because you can't choose r amounnt at a time if r is greater than n
return 0;
int n_fac = solve_factorial(n); //n!
int r_fac = solve_factorial(r); //r!
int nMinusr_fac = solve_factorial(n-r); //(n-r)!
int solve = ((n_fac) / ((r_fac)*(nMinusr_fac))); // plugging in solved factorials into the combination formula
return solve;
}
int run_permutation(int n, int r){
if (n < r)
return 0;
int n_fac = solve_factorial(n);
int nMinusr_fac = solve_factorial(n-r);
int solve = ((n_fac) / (nMinusr_fac)); //plugging in factorials into permutation formula
return solve;
}
int solve_factorial(int f){
if (f-1==0 || f == 0){ //if parameter f is 1 or 0, return 1
int temp = f_value;
f_value = 1; //reset f_value so that f_value remains 1 at the start of every new factorial
return temp;
}
else{ //else multiply f_value by f-1
f_value *= f;
return solve_factorial(f-1);
}
}
This is a mistake:
printf("Number of possibilities: %s", solution);
solution is an int, not a null terminated string: use %d.
Using std::cout which is typesafe, instead of printf(), would have prevented this error:
std::cout << "Number of possibilities: " << solution;
The problematic line is:
printf("Number of possibilities: %s", solution);
You're telling printf that solution is a char*, and so it tries to dereference (char*)solution to print the contents of the "C-string" (presumably when solution has the value 5 in the case of your particular error message).
Change %s to %d, or use std::cout instead of printf to gain type-safety and avoid this sort of issue in the first place.