Why isn't my code working in C on VS Code? - c

Pls check it out and help meeee I'm stuck at it since 2+ hours (the "score" variable and other variables that you might see aren't mentioned here because my original code is too long, so I've just listed the important parts of it):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
while (1) { //using 1 as a condition since "true" doesn't work
char* low(char* question) { // a function used for converting the user input into all lowercased
for (int i = 0; question[i]; i++) {
question[i] = tolower(question[i]);
}
}
printf("1. Is Python a programming language or a creature? ");
char question[25];
scanf("%s", &question);
low(question);
if (strcmp(question, "programming language") == 0 || (strcmp(question, "creature") == 0)) {
printf("Correct! It's both actually 1+ ");
score += 1;
break;
} else {
printf("Invalid Input ");
continue;
}
}
}
Problem: It keeps printing out Invalid input even if the answer is correct

Instead of this:
scanf("%s", &question);
This:
scanf("%s", question);
Reason: question is an array, so when it gets passed as a function parameter, it becomes a pointer to the first element in the array - which is where scanf needs to write to.

Related

Program fails to receive second input

It's just a code to receive user inputs in C program, but fails to do so and accepts null space as input. I have tried fgets() as well and the same thing keeps happening. Please advice on how to fix.
#include <math.h>
#include <stdio.h>
//#include <string.h>
#define len 16
int main(void)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,i=0,j=0;
printf("enter the number of cards:");
n = getchar();
//scanf("%d",&n);
int c1[len][n],card[len][n];
char buf[len];
printf("Enter card number:");
gets(buf);
system("Pause");
return (0);
}
"...code to receive user inputs in c program, but fails to do so and accepts null space as input..."
The reasons your existing code has problems is covered well in the comments under your post.
Consider a different approach: Define the following:
char inBuf[80] = {0};//
int numCards = 0;//Pick variable names that are descriptive (n is not)
int cardNum = 0;
bool isnum;
Then use it in conjunction with printf() etc.
printf("enter the number of cards:");
if(fgets(inBuf, sizeof(inBuf), stdin))//will read more than just a single char, eg. "12345"
{
int len = strlen(inBuf);
isnum = true;
for(int i=0;i<len;i++)
{
if(!isdigit(inBuf[i]))
{
isnum = false;
break;
}
}
if(isnum)
{
numCards = atoi(inBuf);
}
else
{
printf("input is not a number\n"
}
}
printf("Enter card number:");
if(fgets(inBuf, sizeof(inBuf), stdin))
{
...
Repeat variations of these lines as needed to read input from stdin, with modifications to accommodate assignment statements based on user input i.e. an integer (this example is covered), a floating point number, a string (eg. a persons name)
Although there is more that you can do to improve this, it is conceptually viable for your stated purpose...

Program stops working when I input variables [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 2 years ago.
Improve this question
I want to do something in case the username is equal to "admin", but this error appears when I input username and pass.
#include <stdio.h>
#include <stdlib.h>
int main() {
char UserName[100];
char admin[6]="admin";
double Password;
int choice,result;
while (choice!=3){
printf("Username : ");
scanf("%s",&UserName);
printf("Password : ");
scanf("%d",Password);
char admin=admin;
if(strcmp(UserName, admin)&&(Password==1234))
{
printf(" enter your choice : ");
}
}
return 0;
}
I tried to minimize the changes to your code. See my attempt of a possibly working (not tested) alternative
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) { // full definition with prototype
char UserName[100];
char admin[6] = "admin";
int Password; // changed to int
int choice = 0, result; // initialize choice
while (choice != 3) {
printf("Username : ");
// limit input, the & is wrong, check the return value of scanf
if (scanf("%99s", UserName) != 1) exit(EXIT_FAILURE);
printf("Password : ");
// match type of "%" and variable, check the return value
if (scanf("%d", Password) != 1) exit(EXIT_FAILURE);
// char admin = admin; // deleted
// strcmp returns 0 when the strings match
if ((strcmp(UserName, admin) == 0) && (Password == 1234))
{
printf("OK!\n"); // do something
}
// block structure messed up?
printf(" enter your choice : ");
if (scanf("%d", &choice) != 1) exit(EXIT_FAILURE);
}
return 0;
}
this error appears when i input username and pass.
because you have these 2 undefined behaviors in your code :
scanf("%s",&UserName);
whose must be
scanf("%s",UserName);
and 'worst' :
scanf("%d",Password);
whose must be
scanf("%d", &Password);
else scanf try to write to an undefined address being the value of Password which is not initialized
May be the execution continue after scanf("%s",&UserName) but no chance it does after scanf("%d",Password) producing typically a segmentation fault
Note also Password has to be an int, or the format has to be something like "%g" but to use a floating point value for a password is very improbable
Out of that you have an other undefined behavior in
while (choice!=3){
because choice is never initialized, but that time the effect is not 'catastrophic' like it is with scanf("%d",Password);
Also what do you expect with :
char admin=admin;
that line must be removed because there is no reason to have it
And finally a closing '}' is missing before return 0;
I updated your code with some things that were missing:
Added string.h include that was required for strcmp
Removed char admin = admin
Updated the Password scanf to use the proper type
Always try to pay attention to the compiler and activate all warnings as errors when possible.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char UserName[100];
char admin[6] = "admin";
int Password;
int choice = 0;
while (choice != 3)
{
printf("Username : ");
scanf("%s", UserName);
printf("Password : ");
scanf("%d", &Password);
if (strcmp(UserName, admin) && (Password == 1234))
{
printf(" enter your choice : ");
}
return 0;
}
}

How do I compare two strings in if statement in C [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 2 years ago.
I'm pretty new to C; I usually code in C++ before my lecturer told me to code it in C. So how do I compare two strings in if statement in C?
#include <stdio.h>
char name[100],tanya[50],type[100];
int value;
int main()
{
printf("Enter name: ");
scanf("%s", name);
printf("Hello %s", name);
printf( ", Are you interested in Anime? (y/n)");
scanf("%s", tanya);
if (tanya == "y") { // this is the part
printf("Wow, you're an interesting person %s");
do {
} while ();
} else {
printf("good day sir.");
}
return 0;
}
if (tanya == "y")
You do not need to use nor compare strings, when you only want to input a single character like y or n.
Instead use a char object, input a character in it and compare if this character matches y or Y inside the condition of the if statement:
printf(", Are you interested in Anime? (y/n)");
char tanya;
scanf("%c", &tanya);
if (tanya == 'y' || tanya == 'Y')
{....}
If you explicitly want to use strings, you need to compare two strings properly.
In C, one common way to compare two strings is by using the strcmp() function in the header string.h.
In your code it can be used as:
if(strcmp(tanya,"yes") == 0);
to accomplish the comparison and the proof of the if statement to check if both strings are equal.
The whole code shall be like this:
#include <stdio.h>
#include <string.h>
char name[100],tanya[50],type[100];
int value;
int main()
{
printf("Enter name: ");
scanf("%s", name);
printf("Hello %s", name);
printf( ", Are you interested in Anime? (y/n)");
scanf("%s", tanya);
if(strcmp(tanya,"yes") == 0){
printf("Wow, you're an interesting person %s", tanya);
}
else{
printf("Good day sir.");
}
return 0;
}
By the way, it is kind of superficial to kick anybody just because he/she ainĀ“t like animes ;-)
To compare strings in c, you can use strcmp() provided in string.h library.
char a[10],b[10];
if( strcmp(a,b) == 0 ) {
// .. both are identical
}
this function returns 0 or non zero, you'll get details in the ref.
alternatively, while learning, implement your own compare function, like:
#include <stdio.h>
#include <string.h>
bool isEqual(char* a, char* b) {
char* c = a, *d = b;
while(*c != '\0' && *d != '\0') {
if(*c != *d) return false;
c++;
d++;
}
return true;
}
int main() {
char a[10],b[10];
strcpy(a,"name");
strcpy(b,"name");
if(isEqual(a,b)) {
printf("%s %s are same\n",a,b);
}else{
printf("%s %s are not same\n",a,b);
}
return 0;
}
This might help you to think about what's going on under the hood.

s expects argument of type char c but argument 2 has type 'int' warning and bad return

Yes ,I know that this question was already asked for many times ,but none of these helped me to discover the problem (duplicate...yeah). I want to read from input a series of strings into an array and then search from 'First Name'. If the name exist ,I want to display all the data stored in that element of array (I attached the code to undestand easily). When I run it ,I read from keyboard all the data ,but it returns me absolutely nothing.
#include<stdio.h>
typedef struct record {
char name[10],lname[10],phone[10],bday[10];
};
void main() {
struct record rec;
char search;
int i,nr;
printf("\nInput number of records: ");
scanf("%d",&nr);
for (i=0 ; i<nr ;i++) {
printf("First name: ");
scanf("%s",&rec.name[i]);
printf("Last name: ");
scanf("%s",&rec.lname[i]);
printf("Phone: ");
scanf("%s",&rec.phone[i]);
printf("Bday: ");
scanf("%s",&rec.bday[i]);
}
printf("Input the first name for searching: ");
scanf("%s",&search);
for (i=0 ;i<nr;i++) {
if (search == rec.name[i]) {
printf("First name: %s\nLast name: %s\nPhone: %s\nB-day: %s",rec.name[i],rec.lname[i],rec.phone[i],rec.bday[i]);
}
}
}
NOTE: I already replaced
scanf("%s",&rec.name[i]);
with
scanf("%s",rec.name[i]);
but no effect.
I believe there are a lot of problems with your code.
Firstly in this line:
scanf("%s",&search);
You have declared search as only a char, when really you want an array of chars. You also don't need & with search, as an array decays to a pointer to the first element.
It instead should be like this:
char search[10];
scanf("%9s", search); /* %9s to avoid buffer overflow */
You need to make this change to all your other scanf() calls, as this seems to be everywhere in this code.
It also seems that you want to create an array of records(structures), So you might need to make this after getting the value of nr. You can create it like this:
struct record rec[nr]; /* array of nr structures */
This also means calls like this:
rec.name[i]
Don't make sense, as you are iterating over the characters within a name, not over all the records in struct records.
This needs to be instead:
rec[i].name
Secondly, Your using == to compare strings, when you should be using strcmp instead. Using == will only compare the base address of the strings, not the actual contents of strings.
Your line should be this instead:
if (strcmp(search, rec[i].name) == 0) {
If you read the manual page for strcmp(), checking for a return value of 0 means that both strings are equal in comparison.
Lastly, in your first scanf() call:
scanf("%d",&nr);
You should really check the return value of this:
if (scanf("%d", &nr) != 1) {
/* exit program */
}
Note: For reading strings, you should really be using fgets instead. You can try upgrading to this later, but I think it is better to understand these basics first.
Here is working example of what your program should do:
#include <stdio.h>
#include <string.h>
#define STRSIZE 10
typedef struct {
char name[STRSIZE+1]; /* +1 to account for null-btye at the end */
char lname[STRSIZE+1];
char phone[STRSIZE+1];
char bday[STRSIZE+1];
} record;
int main() {
char search[STRSIZE+1];
int i,nr;
printf("\nInput number of records: ");
if (scanf("%d", &nr) != 1) {
printf("Invalid input.\n");
return 1;
}
record rec[nr]; /* array of records */
for (i = 0; i < nr ; i++) {
printf("First name: ");
scanf("%10s", rec[i].name);
printf("Last name: ");
scanf("%10s", rec[i].lname);
printf("Phone: ");
scanf("%10s", rec[i].phone);
printf("Bday: ");
scanf("%10s", rec[i].bday);
}
printf("Input the first name for searching: ");
scanf("%10s", search);
for (i = 0; i < nr; i++) {
if (strcmp(search, rec[i].name) == 0) {
printf("First name: %s\nLast name: %s\nPhone: %s\nB-day: %s\n",rec[i].name,rec[i].lname,rec[i].phone,rec[i].bday);
} else {
printf("Record not found.\n");
}
}
return 0;
}
The numeric input leaves a new line character in the input buffer, which is then picked up by the character input. when numeric input with scanf() skips leading white space, character input does not skip this leading white space.
Use a space before %c and it will help you cause if space is not used then a buffer added with value .so that use space before %c
scanf(" %c",&rec.name[i]);

Prompt for input and print a response with only one printf()?

C-code only: Ask user if they are married or not. User must input 0 for false. User must input any other character for true. Do it using only one printf.
Ok, so I always turn to stackoverflow as a last resort, because I am trying to figure it out. This, is what I came up with but I get errors and I have done other things like take out scanf("%f", &t), because that is essentially unnecessary. I also made char married[3]; char married[] ="; instead but that doesn't work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char married[3];
unsigned long t;
int f;
scanf("%f", &t);
scanf("%d", &f);
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);
if (f == 0)
{
married == "no";
}
else
married == "yes";
return 0;
}
Thanks the help is appreciated. Please go easy on me just learning...
I'm not sure you are interpreting the question correctly. It says to print whether the person is married or not. So that's the expected output. It suggests you can do that with one printf. It does not mean the whole program only has one printf so you are allowed to have another printf for the user prompt. It just means avoid using two printfs for the output (one for YES and another for NO). One way to do this is to use the ? operator.
For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int married = 1;
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
scanf("%d", &married);
printf("You %s married\n", married ? "ARE" : "ARE NOT");
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char married[4]; //Space for 'yes' + the NUL-terminator
//unsigned long t; Why do you have this?
int f = 1; //Initialize variables
//scanf("%f", &t); ??
//scanf("%d", &f); Wrong place
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
scanf("%d", &f); //scan input after printing
if (f == 0)
strcpy(married, "no");
else
strcpy(married, "yes"); //Copy strings using strcpy function
return 0;
}

Resources