if statement with nested functions will not execute - c

#include <stdio.h>
main()
{
char name[30];
int age;
printf("Please enter your name: ");
scanf("%s", name);
printf("How old are you %s: ", name);
scanf("%d", age);
if (strcmp(name, "Abs") == 1 && age == 25)
printf("You are the CHOSEN one!\n");
else
printf("You are a wankstain!\n");
fflush(stdin);
getchar();
}
The if statement seems to ignore the right answer, i have also tried to put the age in brackets to no avail.

Why not read the manual page for strcmp. You been to check for zero.
Ditto for scanf - it does return a value that needs to be checked.
Use braces - prevents problems in the future.
You do not need to flush stdin.
(see http://linux.die.net/man/3/strcmp and http://linux.die.net/man/3/scanf)

Related

comparing strings and printing stored strings in C

I am having trouble getting this program to print the strings I enter properly. It keeps telling me that I have not entered data, even when I have. I also can't get the strings to compare to run my if statement. Thank for any help.
#include <stdio.h>
//function prototype
void enterPerson();
void enterChoice();
//global variables
char person[30];
char choice;
int main(void) {
enterPerson();
enterChoice();
printf("Please try the Precipitation Program again.\n");
return 0;
}
void enterPerson(){
// Ask for person name
printf("Please enter name:\n");
scanf("%s", &person);
//-------------------------------------------
printf("person is %s\n", person);
//-------------------------------------------
}
void enterChoice(){
//initialize choice
choice = "M";
//ask what they choose
printf("Do you choose test or rate? (Enter T for test R for rate)\n");
scanf("%c", &choice);
printf("Xchoice is: %c\n", choice);
if ((choice == 'T')||(choice == 'R')){
printf("choice is: %c\n", choice);
}
else{
printf("Incorrect or no data was input at this time\n");
}
}
As mentioned in comments, there are at least 3 problems:
scanf("%s", person); - do not take the address of char array.
scanf(" %c", &choice); - insert space to ignore whitespace.
choice = 'M'; - "M" is a string literal, while choice is char.
There is a linefeed (0xa) character left in the input buffer. You can see it by printing the choice variable after your scanf line with:
scanf("%c", &choice);
printf("c: %x\n", choice);
There are several options to get rid of this. Easiest is explained here.
Also there is a problem in:
scanf("%s", &person);
Character array name in C points to the first character, so you should fix this with:
scanf("%s", person);

If statement not working for marital status

I am creating a program which requires user to enter their marital status.
i want to be able to ask them Yes or No and then use if statements .
my code just skips the if block and prints the else block.
#include<stdio.h>
int main(void)
{
int age;
char marr;
printf("Please enter your age: \n");
scanf_s("%d",&age);
getchar();// getchar() is being used to clear any buffer of any remaining keystrokes that might stll be stored.
printf("Are you married ? (y/n)\n");
scanf_s("%c", &marr);
if (marr == 'y')
printf("Married\n");
else
printf("Unmarried\n");
}
for some reason, whatever I input, i still get the output as unmarried,
no idea why.
Use scanf() instead of scanf_s() in this case or you'll need a buffer size argument if your input parameter is a character. Too you can place a space before %c in the scanf()-statement instead of your getchar()-command.
#include<stdio.h>
int main(void) {
int age;
char marr;
printf("Please enter your age: \n");
scanf("%d",&age);
printf("Are you married ? (y/n)\n");
scanf(" %c", &marr);
if (marr == 'y')
printf("Married\n");
else
printf("Unmarried\n");
}

scanf() to get in the string on the second time

What is wrong with the scanf() to get in the string on the second time, I can't input my string on the second time.
I am not sure with the error that occurs, I can't get this program function well
#include <stdio.h>
#include <stdlib.h>
int main()
{
//variables decleration
char staff_name1[31];
char staff_name2[31];
float sales1, sales2;
//input
printf("Enter staff name\t> ");
scanf("%[^\n]s", staff_name1);
printf("Enter sales amount\t> ");
scanf("%f", &sales1);
printf("\nEnter staff name \t> ");//ERROR,CAN'T INPUT MY STRING
fflush(stdin);
scanf("%[^\n]s", staff_name2);
printf("\nEnter sales amount\t> ");
scanf("%f", &sales2);
printf("\n");
//output
printf("Staff Name\t\t\t\tSales Amount\n");
printf("===================\t\t=============\n");
printf("%-20s \t%12.2f\n", staff_name1, sales1);
printf("%-20s \t%12.2f\n", staff_name2, sales2);
}
my output of this code is as below:
warning: this program uses gets(), which is unsafe.
Enter staff name > kh s
Enter sales amount > 134.14
Enter staff name >
Enter sales amount > 141243.14
Staff Name Sales Amount
=================== =============
kh s 134.14
141243.14
I can't input the second staff name. Can anyone please help me solve this??
fflush(stdin);
is undefined behaviour in standard C. To flush the newline character, you could simply use getchar() instead.
printf("\nEnter staff name \t> ");
getchar();
scanf("%[^\n]s", staff_name2);
I would also use fgets() instead of scanf to read a line and trim the newline if necessary, which offers better control over invalid inputs being entered by user and against buffer overflows.
You have three problems.
I see that you use %[^\n]s. It is wrong. The s isn't part of the %[ specifier. So use %[^\n] instead of %[^\n]s
After you enter the value for sales1, you press Enter. This character stays in the stdin(standard input stream). And when the next character for %[^\n] is \n, it will fail. Fix this problem by adding a space before %[^\n].
Using fflush on stdin invokes Undefined Behavior as per the C11 standard, although the behavior is well defined in some implementations. It is better to remove it so that your code will be more portable.
Additional notes:
You can limit the amount of characters to be scanned so that you can avoid buffer overflows.
You can check the return value of scanf to make sure it is successful. All the scanf in your program will return 1 on success.
Fixed Program:
#include <stdio.h>
#include <stdlib.h> //Unused header
int main()
{
char staff_name1[31];
char staff_name2[31];
float sales1, sales2;
printf("Enter staff name\t> ");
if(scanf(" %30[^\n]", staff_name1) != 1)
{
printf("Could not scan staff_name1");
return -1; //Exit main with a return value of -1
}
printf("Enter sales amount\t> ");
if(scanf("%f", &sales1) != 1)
{
printf("Could not scan sales1");
return -1; //Exit main with a return value of -1
}
printf("\nEnter staff name \t> ");
//fflush(stdin); UB!
if(scanf(" %30[^\n]", staff_name2) != 1)
{
printf("Could not scan staff_name2");
return -1; //Exit main with a return value of -1
}
printf("\nEnter sales amount\t> ");
if(scanf("%f", &sales2) != 1)
{
printf("Could not scan sales2");
return -1; //Exit main with a return value of -1
}
printf("\n");
//output
printf("Staff Name\t\t\t\tSales Amount\n");
printf("===================\t\t=============\n");
printf("%-20s \t%12.2f\n", staff_name1, sales1);
printf("%-20s \t%12.2f\n", staff_name2, sales2);
}

C prompt ordering for reading string with getchar() [duplicate]

This question already has answers here:
Why is getchar() reading '\n' after a printf statement?
(3 answers)
Closed 9 years ago.
This is a newbie question. I am new to C programming. I have the following code which does not prompt for 'Name' Onece the 'Age' is entered, it bypass the 'Name section.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
printf("Enter age : ");
scanf("%d", &age);
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
After reading first prompt it bypass the second prompt which is using getchar() function. But if I change the order of prompt to ask for 'Name' first and then 'Age' it works fine.
The working code.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Enter age : ");
scanf("%d", &age);
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
My coding IDE is CodeBlock and my compiler is GNU C Compiler (mingw32-gcc.exe)
Please help me to breakthrough.
A few improvements/advices to the code in the question:
the type of the return value of getchar() is int, so the type of ch also should be int
you could (and should, I believe) use format %s to read the name, this is easier and the leading white spaces in the input stream would not be a problem
the user of the code could give a name which contains more than 30 characters, and this input could crash your program, so you should protect your code for this possibility. You have two options:
a. use format '%29s" to read the name
b. change the definition of name to char *name, read it by scanf("%ms", &name);, and call free(name); after you do not need it anymore
Here is an example, in which the name can be very long and can include spaces:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
char *name;
int age;
printf("Enter name: ");
scanf("%m[^\n]", &name);
printf("Enter age: ");
scanf("%d", &age);
printf("Name: %s\n", name);
printf("Age : %d\n", age);
free(name);
exit(EXIT_SUCCESS);
}
And here is a run of it:
$ ./a.out
Enter name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Enter age: 12
Name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Age : 12
In first code the \n character left behind by the scanf is read by getchar. This makes the condition (ch = getchar())!='\n' in while loop false and the loop body never get executed.
You need to consume that \n character which comes up to the buffer along with the age you entered on pressing Enter key.
Putting the statement
while(getchar()!='\n');
after the scanf will consume all of the newline characters.
Your second code is working fine because %d skips white-space characters unlike %c specifiers.

User Input to File

I'm creating a program that should create a structure of a list of people entered by the user; the only problem I'm having is getting the user input data to appear in the text file. Anyone know how to do this? Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct person{
char name[20];
int age;
struct person *next_ptr;
} PERSON;
int main (void){
struct person PERSON;
FILE *fp;
char ans, ch;
int ppl=0;
fp=fopen("person_struct", "w");
if(fp != NULL){
while(ppl<25){
printf("Would you like to add a person to the list? [y/n] ");
scanf("%c", &ans);
if(ans == 'y') {
printf("\nEnter a name:\n");
scanf("%s", PERSON.name);
fprintf(fp, "%s",PERSON.name);
printf("\nEnter age:\n");
scanf("%i", &PERSON.age);
fprintf(fp, " %i\n", PERSON.age);
}
else {
ppl=25;
}
ppl++;
}
fclose(fp);
}
printf("\n\n\n");
system("pause");
return 0;
}
Youe scanf statement is wrong you forgot ampersand & operator before PERSON.age its int
scanf("%i", PERSON.age);
^ & missing
correct is:
scanf("%i", &PERSON.age);
You have two scanf stamens in your code to inputs from user one for string to scan name.
scanf("%s", PERSON.name);
This is correct and No need of & before string. But age is int and to scan int.float you need to add & before variable that is why added ampersand & before PERSON.age.
ref: scanf
Second:
fputs(PERSON.age, fp); is wrong syntax of fputs is:
int fputs( const char *str, FILE *stream );
^ you are passing int
first argument should be const char* but your are passing int
fputs(PERSON.age, fp);
^ wrong , age is int not char*
When you need formatting input/output prefer printf and scanf functions, My suggestion change your read/write like: (read comments)
printf("Enter a name:\n");
scanf("%s", PERSON.name); // here is No & because `name` is string
scanf("%i", &PERSON.age); // age is `int` so & needed
fprintf(fp,"%s %i\n",PERSON.name, PERSON.age);
EDIT: Because you commented, your code is working after these rectifications, see
$ gcc x.c -Wall
$ ./a.out
Would you like to add a person to the list? [y/n]y
Enter a name:
yourname
14
Would you like to add a person to the list? [y/n]y
Enter a name:
firendName
15
Would you like to add a person to the list? [y/n]n
sh: 1: pause: not found
$ cat person_struct.txt
yourname 14
firendName 15
In addition to Grijesh's answer:
Please explain scanf("%s", &ans);. How many characters can you store in ans? How many characters does the string "y" require to store? Verify your beliefs: printf("sizeof ans: %zu\n" "sizeoof \"y\": %zu\n", sizeof ans, sizeof "y");
Perhaps you meant: if (scanf("%c", &ans) != 1) { /* assume stdin has closed or reached EOF */ }. Note the %c, which will read only one character into ans.
Alternatively, if you change ans to an int, you can use: ans = getchar();
edit: In short, I think your loop should look something like this:
for (size_t ppl = 0; ppl < 25; ppl++){
int ans;
printf("Would you like to add a person to the list? [y/n]");
do {
ans = getchar();
while (ans >= 0 && isspace(ans));
if (ans != 'y') {
break;
}
printf("Enter a name:\n");
if (scanf("%s", PERSON.name) != 1 || scanf("%i", &PERSON.age) != 1) {
break;
}
fprintf(fp, "%s %i\n", PERSON.name, PERSON.age);
}

Resources