I am trying to debug a program which were I am getting the values 'S' or 'P' from standard input. My function calc_resistance() needs to distinguish between these two cases as well as a case were neither 'S' nor 'P' has been entered. The program always evaluates to the third case (neither 'S' nor 'P'`), why is this so?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
float calc_resistance(char conn) {
float retval = 0.0;
if (conn == 'S') {
retval = 1;
}
else if (conn == 'P') {
retval = 2;
}
else {
retval = -1;
}
return retval;
}
int main() {
char connection_type[25];
float resistance = 0.0;
while(1) {
printf("Enter 'S' or 'P': ");
scanf("%s", connection_type);
if(strlen(connection_type) != 1 ||
(strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25))) {
printf("Answer not understood. Enter 'S' or 'P'.\n");
continue;
}
break;
}
resistance = calc_resistance(connection_type);
printf("Connection type: %f", resistance);
}
The mistake you're doing is to pass an array to the calc_resistance() function when it is defined to accept only a single char.
Seeing the input pattern, connection_type doesn't need to be an array, with the help of %c format specifier, you can easily make connection_type a single char variable to work on the input.
You can read more about this on the man page of scanf(). Also, after each iteration, don't forget to sweep out the remaining newline.
Moral of the story :: Enable compiler warnings and pay heed to them.
You want to detect the first two cases right? if yes then try this one instead of passing the whole address in your function calc_resistance(connection_type) only pass one character then try, You can modify the code as below.
#include
#include
#include
float calc_resistance(char conn)
{
float retval = 0.0;
if (conn == 'S')
{
retval = 1;
}
else if (conn == 'P')
{
retval = 2;
}
else
{
retval = -1;
}
return retval;
}
int main()
{
char connection_type[25];
float resistance = 0.0;
while(1)
{
printf("Enter 'S' or 'P': ");
scanf("%s", connection_type);
if (strlen(connection_type) != 1 || (strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25)))
{
printf("Answer not understood. Enter 'S' or 'P'.\n");
continue;
}
break;
}
resistance = calc_resistance(connection_type[0]);
printf("Connection type: %f", resistance);
}
Related
please help me i am struggling with this it keeps giving me errors on errors btw LABEL 2 leads to the main part
#include <stdio.h>
void main()
{
int a,b,c;
char d[10],e[10];
Label:
printf("Username of the agent: ");
scanf("%s",d);
printf("Password: ");
scanf("%s",e);
if(d=="Vayush" && e=="Vasireddy")
{ goto Label2;}
else
printf("wrong username and password\n");
goto Label;
}
if(d=="Vayush" && e=="Vasireddy")
is comparing pointers to string literals, thats wrong because you want to compare contents and not addresses. The compiler is telling you to use the standard function strncmp instead of ==, in this case strcmp can do the job:
#include <stdio.h>
#include <string.h> // strcmp
int main(void) // Use a valid signature
{
// Use meaningful names for your vars
char usr[10];
char pwd[10];
// Do not use goto, loop until you get valid values
while (1)
{
printf("Username of the agent: ");
// scanf return the number of input items successfully matched or EOF
int n = scanf("%9s", usr); // %9s in order to avoid buffer overflows
if (n == EOF) { break; }
if (n == 1)
{
printf("Password: ");
n = scanf("%9s", pwd);
if (n == EOF) { break; }
if ((n == 1) &&
(strcmp(usr, "Vayush") == 0) &&
(strcmp(pwd, "Vasireddy") == 0))
{
break;
}
}
printf("wrong username and password\n");
}
}
What I'm exactly trying to achieve is: You enter your name, get a response like 'your name is', and if you enter a number you get a response like 'invalid input' which loops you back to the 'Enter your name' part
#include <stdio.h>
char i[20];
int result;
int main()
{
void findi(); // im trying to loop it back here if a number is entered instead of a character
printf("Enter your name\n");
result = scanf("%s", &i);
while(getchar() != '\n'){ //dont know how to make it work without the '!'
if(result = '%s'){
printf("Your name is: %s", &i);
return 0;
}
else{
printf("Invalid input"); //doesnt work
findi();
}
}
}
//program just ends after a character is entered instead of continuing
Using &i (char(*)[20]) for %s (expects char*) invokes undefined behavior.
The condition result = '%s' (assign implementation-defined value to result without checking its value) looks weird.
Calling findi() (not disclosed here) from main() need not mean a loop.
Try this:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char i[20];
printf("Enter your name\n");
/* an infinite loop (loop until return or break) */
for (;;) {
int number_exists = 0, j;
/* limit length to read and check the result*/
if (scanf("%19s", i) != 1) {
printf("read error\n");
return 1;
}
/* check if a number is entered */
for(j = 0; i[j] != '\0'; j++) {
if (isdigit((unsigned char)i[j])) {
number_exists = 1;
break;
}
}
/* see the result */
if (number_exists) {
/* one or more number is entered */
printf("Invalid input\n");
} else {
/* no number is entered : exit from the loop */
printf("Your name is: %s\n", i);
break;
}
}
return 0;
}
Whenever I enter the choice of 2, it does not execute the view_list() function. Instead it start it from first function which is new_acc(). Also the else is not working. How to solve this problem?
#include <stdio.h>
#include <stdlib.h>
int new_acc();
int view_list();
int main(){
int one=1, two=2;
int new_account, list;
printf("%d. Create new account\n",one);
printf("%d. View customers list\n",two);
printf("Enter you choice: ");
if (scanf("%d",&one)){new_account = new_acc();} // calling a function
else if (scanf("%d",&two)){list = view_list();} // calling a function
else {printf("Sorry this is not the correct option"); break;}
return 0;
}
int new_acc(){
char name;
printf("Enter your name: ");
scanf("%s",&name);
return 0;
}
int view_list(){
printf("view list");
return 0;
}
The return value of scanf() is the number of values it returns, not the actual value it self. Code should be:
int value = 0;
scanf("%d",&value);
if(value == one){new_account = new_acc();}
else if (value == two){list = view_list();}
else {printf("Sorry this is not the correct option"); break;}
Other recommendations:
The final break is not doing anything;
Indent your code it makes it much easier to read:
int value =0;
scanf("%d",&value);
if(value == one)
{
new_account = new_acc();
}
else if (value == two)
{
list = view_list();
}
else
{
printf("Sorry this is not the correct option");
}
The return value of scanf() is number of data read.
printf("Enter you choice: ");
if (scanf("%d",&one)){new_account = new_acc();} // calling a function
else if (scanf("%d",&two)){list = view_list();} // calling a function
else {printf("Sorry this is not the correct option"); break;}
should be like
printf("Enter you choice: ");
if (scanf("%d",&one)) != 1) { puts("input read error"); return 1; }
if (one == 1){new_account = new_acc();} // calling a function
else if (one == 2){list = view_list();} // calling a function
else {printf("Sorry this is not the correct option"); return 1;}
or
printf("Enter you choice: ");
if (scanf("%d",&one)) != 1) { puts("input read error"); return 1; }
switch (one) {
case 1: new_account = new_acc(); break; // calling a function
case 2: list = view_list(); break; // calling a function
default: printf("Sorry this is not the correct option"); break;
}
By the way, executing your new_acc() is dangerous.
%s specifier will accepts positive-length string while your buffer has space for only one character.
Even input of one-character string will cause buffer overrun because there will be terminating null character.
It should be like
int new_acc(){
char name[1024]; /* allocate an array */
printf("Enter your name: ");
scanf("%1023s",name); /* specify length limit (buffer size - 1 (terminating null character)) to avoid buffer overrun */
return 0;
}
I want so that when the user enters e it will run my function called enter and scan in values but all I get is VECRQ?:, why is this? Did I call upon the function wrong?
I tried having the while loop to 1 also instead of menuoption != 'q' didn't work. I was thinking that with the menuoption is not equal to 'q' it will keep the loop running until the user actually enters 'q' to shut the program off.
#include <stdio.h>
int enter(int measurments[], int nrOfmeasurments)
{
while(nrOfmeasurments<10)
{
printf("Enter measurment #%d (or q to quit): ",nrOfmeasurments+1);
int oneMeasurment;
int readInteger = scanf("%d",&oneMeasurment);
if(readInteger)
{
measurments[nrOfmeasurments] = oneMeasurment;
nrOfmeasurments ++;
//return nrOfmeasurments;
}
else
{
char tmp;
scanf(" %c",&tmp);
break;
}
}
if(nrOfmeasurments==10)
{
printf("Array is full\n");
}
return nrOfmeasurments;
}
int main(void)
{
int measurments[10];
int nrOfmeasurments;
char menuoption;
printf("Measurment tool 2.0\n");
while (menuoption != 'q')
{
printf("VECRQ?:\n");
scanf(" %c",&menuoption);
if (menuoption == 'e')
{
//int MeasurmentData[10];
//int nrOfmeasurments;
//enter(measurments, nrOfmeasurments);
nrOfmeasurments = enter(measurments, nrOfmeasurments);
}
else if(menuoption == 'v')
{
}
else if(menuoption == 'c')
{
}
else if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
}
Don't forget to init your variables with default values. Your problem is that nrOfmeasurments is not initialized and have some trash value. Also, set a default value to menuoption for some non q char to be sure, that your loop will be executed at least one time
I am trying to write a while loop which only runs as user input is 'F' or 'C'. However, my while loop seems doesn't work. Could you show me what is wrong with my scanf and while loop condition
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
response is uninitialized. Your code hasn't even gotten to the scanf() yet. Consider changing it to a do-while loop.
You have to initialize response, try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
response = 'F';
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
and you can of course do it this way
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
/* since you don't check for `scanf()`'s return value,
* this prevents undefined behavior
*/
response = 'F';
do {
printf(" Please enter F or C\n");
scanf(" %c", &response);
} while (response == 'F' || response == 'C');
return 0;
}
Your loop runs as long as response is 'F' or 'C'. What you need is
while (response != 'F' && response != 'C')
Also, response is not initialized. Start with
char response = '\0';
There are two common ways to do a terminate-on-input loop in C:
do {
...get input...
do_stuff();
} while (...input does not indicate exit...);
or
while (1) {
...get input...
if (...input indicates exit...) break;
do_stuff();
}
I think the latter might work better for your case:
while (1) {
printf(" Please enter F or C\n");
scanf(" %c", &response);
if ('F' == response) {
do_f();
} else if ('C' == response) {
do_c();
} else {
break;
}
}