C programming: IF statements - c

I need help on a problem on C programming. I was wondering if there is a way to have a user input a word to the console and it would display whatever you program it to. Heres a example of what I want to do
int Choice;
int Energy = 100;
printf ("Type 2817!\n");
scanf ("%s", &Choice);
if(Choice == 2817)
{
printf ("You have started the game\n\n\n\n\n\n\n\n\n\n\n");
}
else if(Choice == "Energy") //This isnt working in my compiler.
//Apparently the == sign is the underlined error
{
printf("%d", Energy);
}
So far I can only type numbers but I want to be able to type words and be able to use a command. SO basically I want to be able to type "Energy" and it will show the amount of energy you have (printf ("%d", Energy)
Please help,
Thank you for reading.

You have enter wrong datatype when comparing the choice (int type) with a string text. In C/C++ unlike dynamic programming language, you cannot compare int with strings without properly converting either of them. You use strcpy for comparing string and == for comparing int.
Then your programming will run.

I'm not sure what your program is trying to do, but let me concentrate on the few obviously incorrect lines.
First, in
int Choice;
scanf ("%s", &Choice);
you have the wrong type for Choice: it is "int" whereas it should be a static array of char (let's say char Choice[32]). In this case you also have to remove the "&" before "Choice" in the scant, so that the code becomes:
char Choice[32];
scanf ("%s", Choice);
Moreover, in
else if(Choice == "Energy") //This isnt working in my compiler.
you are trying to compare two strings with the operator "==". This does not work in C. You should use the function "strcmp" the following way:
#include<string.h>
[...]
else if(strcmp(Choice, "Energy")==0)
You'd even better use the following to prevent any buffer overflow
else if(strncmp(Choice, "Energy", 32)==0)
(replace 32 with the maximum number of elements in Choice)
Edit Note that you should change the first comparison too from
if(Choice == 2817)
to
if(strncmp(Choice, "2817", 32))
because Choice is not an int anymore...

The best way to approach this problem would to be to make Choice a string, then compare it to string values, or extract data from the string (for example with atoi) and assign it to other variables. C is a statically typed programming language, an int cannot become (or be compared to) a string because they are not of the same type. If you want arbitrary data from the user, the best way to approach that problem is probably to use a string. :-)

Read your input as array of chars
example
char bleh[250];
scanf ("%s", bleh);//or scanf ("%s", &bleh[0]);
and then use strcmp command to compare two arrays
strcmp(&bleh[0], "blabla"); //function will return 0 if two arrays match
hope this helps

"String" is const char *, you cannot compare using == in C++. You need to use strcmp to compare string.
strcmp returns zero if strings are same.

Few mistakes in the code.
use strcmp() to compare string.
Declare int Choice; to char Choice[50]
Remove & while reading string in scanf()
Comparing with if(Choice == 2817) is not correct. use if(strcmp(Choice , "2817") == 0)

Related

Can I make a while loop using Char, instead of Double?

I'm new to this, and I'm assuming there is an easy solution to my issue. My first formula works exactly how I'd like it to. If the user input matches dogage99, then it prints "Correct". I want to do something similar, but using words instead of numbers. I've switched double for char, and adjusted the formula accordingly.
The problem is, the second formula doesn't work as I expected. When the user input matches dogname1, it doesn't print "Correct", it just continuously asks to "enter dog name".
What can I do to fix my issue?
int main()
{
double guess99;
double dogage99 = 3;
while (guess99 != dogage99) {
printf ("enter dog age:");
scanf ("%lf", &guess99);
}
printf ("Correct\n");
char guess1;
char dogname1= "spot";
while (guess1 != dogname1) {
printf ("enter dog name:");
scanf ("%s", &dogname1);
}
printf ("Correct\n");
First of all the line
char dogname1= "spot";
should be corrected to
char *dogname1= "spot";
This way the char array dogname1 will be correctly initialized as a character array and will contain the null-terminator "\0" at the end of the array.
You must also ensure, that guess has enough memory secured, so you must either create a array of sufficiently enough bytes (for e.g. 256), or dynamically allocate memory. In this example I would do the first changing char guess1; to char guess1[256];
Knowing that guess1 has sufficiently enough memory and a null-terminator we can next rewrite the while loop to
while(strcmp(guess1, dogname1)) { ... }
The strcmp() standard library function returns 0 if and only if both character arrays match lexicographical and that is also the time we want to go out of the loop. It is also important to know, that you must ensure both arrays have null-terminators when using this exact function. If you cannot ensure it, then use strncmp().
For reference about all the different compare functions and their implications: https://www.ibm.com/docs/en/aix/7.1?topic=s-strcmp-strncmp-strcasecmp-strcasecmp-l-strncasecmp-strncasecmp-l-strcoll-strcoll-l-subroutine
I am sure the compiler is complaining big time at you about
char dogname = "spot";
in c the type char represent a single character not a string. Strings in C are a sequnce of characters followed by a char set to \0. The compiler will set that up for you if you do
char *dogname="spot";
It will allocate 5 bytes , load s,p,o,t,\0 into those bytes and set the dogname variable to point at the first character.
If you want to compare string you have to use the c library function called strcmp - https://man7.org/linux/man-pages/man3/strcmp.3.html.
Alos you need a char array to receive the input. We just say we want 50 characters. Must also tell scanf to not allow more than 50 charaters. Note that I asked for 51 character array to allow for the trailing 0 that must always be present.
so your loop becomes
char guess1[51];
char *dogname1= "spot";
while (guess1 != dogname1) {
printf ("enter dog name:");
scanf ("%50s", guess1);
}
printf ("Correct\n");
note you must #include string.h
check this out https://www.tutorialspoint.com/cprogramming/c_strings.htm

return value ignored: 'scanf' (closed)

I'm writing a program with C and this is one of my functions:
void group3()
{
char select[5];
printf("\nDetails etc.");
printf("\nPlease confirm Yes/No if you would like to subscribe:");
scanf("%s", select);
if (select == "Yes")
printf("Good.");
else
{
printf("Alright.");
main();
}
}
But when I try to compile and debug the program, a warning called "return value ignored: 'scanf'" appears. I noticed that the warning appears when I'm running scanf for integers too but the program still works for integers. However, when I try to scanf for strings, it doesn't work. I've tried using getchar() but the same warning occurs for getchar(). I've also tried using scanf_s but the same problem appears when I try to scanf_s for strings. I've also defined _CRT_SECURE_NO_WARNINGS in my program. Would really appreciate it if someone could explain to me how I can eliminate this warning from occurring/get the scanf or getchar to work with strings.
edit: thanks to some helpful users i found out that the problem isn't because the string wasn't read, but because i cannot compare strings using the if statement this way. the answer is in the comment section and i can't select it as the correct answer to this but this question is closed. thank you :)
The problem is that the return value of scanf() is ignored, so don't ignore that to eliminate the warning.
scanf() returns the number of data read on success and negative number on error, so it is useful to check if it successfully read required things.
Example:
if (scanf("%4s", select) != 1) {
fputs("read error\n", stderr);
exit(1);
}
Also it is good to read the length to read to avoid buffer overrun.
This is also done in the above example.
One more point is that select == "Yes" is not a correct way to compare strings in C.
This is comparing pointers and it won't be true because the array and the string literal are stored in differenct places in memory.
strcmp() function from string.h is useful to compare strings.

What do I do now?

It may be really simple, but I don't really know what to do now.
I just recently got in programming and I thought I should start by learning C, I know a few stuff here and there but I just recently got into this problem and I can't figure it out.
Im trying to make a register/login system that stores the credentials into strings using scanf(), I don't really know how to get the login part to work. Do I need to create more strings and store the input there? Or how can I compare the user's input to the value in the strings?
My code is currently looking like this:
#include<stdlib.h>
#include<time.h>
char user[30] = "";
char password[30] = "";
char yn[30] = "";
char Y[1] = "Y";
char N[1] = "N";
int main() {
printf("Register\n");
printf("The User or Password can't be longer than 30 characters\n");
printf("User: \n");
scanf("%s", &user);
if (user == NULL)
printf("User can't be empty\n");
else
printf("Password: \n");
scanf(" %s", &password);
if (password == NULL)
printf("Password can't be empty\n");
printf("User saved as: \n");
printf("%s\n", &user);
printf("Password saved as: \n");
printf("%s\n", &password);
printf("Is this correct?\n");
printf("Y/N\n");
scanf("%s", yn);
if(yn == Y){
printf("\e[1;1H\e[2J");
}
if(yn == N){
printf("Restarting...");
}
printf("Login\n");
printf("User: \n");
}
It all works well (except I can't figure out how to clear the console before asking to log in, this wont work printf("\e[1;1H\e[2J");), I even managed to print out the user's input to the console for him to make sure its correct and I made a (Y/N) thingy. Can someone help me please?
You can create functions instead of having them all in the main.
Create a register function that saves the data and a login function that asks for data as parameters and the call it in the main.
Maybe you can create a simple menu.
When you first learn a language, you discover certain patterns of how it can be used. Some of your problems come from overusing patterns where they don't make sense.
For example, you know you can compare two variables with == but that compares values, and in some cases you are comparing references as if they were values. References are memory addresses, and if you have two letters Y in RAM then they are distinct, having two different references, even if their value is the same.
Since a lot of your processing uses strings, read through the functions available when you #include <string.h> You will hear a lot about how some of these are unsafe to use; for now I recommend skipping safety arguments as they make more sense after you know how to call the functions.
For example
if (yn == Y) {
is not going to give you the desired result, but
if ( strcmp( toupper( yn[0] ), "Y" ) == 0 ) {
will give you the desired result. As in most cases, there are other ways to write the same logic; but, for those who want to offer more efficient ways of checking yn, this is an example designed to show off string functions.
Strings in C are not single values. They are an address (sometimes called a reference) to a pieced of memory, which if you keep reading char-by-char should eventually end in a NULL character, a char containing the number 0. This means that they cannot be compared directly as in yn == Y because you are comparing two memory addresses, not two sequences of chars.
The above example is a simplification of what strings can be. It's a good enough of a definition for a beginner; but, over time you will find that this definition is very old, and has been revised over time. The problem is that a char can only hold 8 bits, so when more than 256 distinct values were needed, a solution was created to hold more values.
The first solution was to use a "wide character" called a wchar, which has the type of wchar_t. This is like a char, but it holds 16 bits. This started the whole "char" vs "wchar_t" problems. For now you can ignore them, but be aware that if you ever work with wchar_t you need wchar compatible functions.
The second solution was to introduced Unicode, which provides enough characters that nearly every language can be written within Unicode, even most dead languages, emojis, upside down text, etc. Unicode doesn't have a single way of representing its characters, but there are two popular ones for the beginning programmer. UTF-32, which used 32 bytes for each character, is popular because it is easy to program. UTF-8 is popular because it is the effective "correct choice" for the Internet due to it extending ASCII and being the format of the Internet.
Once you get familiar with strings, you might want to spend some quality time with UTF-8.
Good luck.

Trouble with C else, if and scanf

I am new to C and I'm making my first "decent" program. I am facing trouble with my code.
char username[] = "root";
char usernametry[10];
scanf("%s",usernametry);
if (usernametry == username)
{
printf("Welcome ROOT user\n");
}
else
{
printf("Try again\n");
}
Whenever I execute my program, everything works; however, when I try to log in and type root as the username, it returns Try again. Can someone suggest why this is happening? I am very new to C so I apologize for my lack of C knowledge.
usernametry and username are arrays of type char. When you do usernametry == username, you are not comparing if two strings are equal, you are comparing the memory address of the first char in usernametry with the memory address of the first char in username. In order to compare if two strings are equal, you should use strcmp. Also, consider replacing %s in your scanf with %9s so that usernametry will never exceed 9 chars (which would have been a buffer overflow, as the 10th char needs to be '\0', the null character, which is used to terminate C-style strings).
You can't compare strings using ==, this is not a that-high-level-language. See strcmp() for comparing strings.
Incidentally, what if someone enters a name longer than 10 characters? You're drifting towards a buffer overflow bug in your code ;-)
use strcmp() functions to compare 2 strings instead of ==
use of == is wrong because in this case you compare address of usernametry and username and of course they are always differents.
if(strcmp(usernametry, username) == 0) // return 0 if equal !=0 if not equal
Use strcmp to compare two strings:
if(!strcmp(usernametry,username))
Your variables are not the same pointer.
Replace by:
if (!strcmp(usernametry, username))

loop does not terminate [duplicate]

This question already has answers here:
Why is "a" != "a" in C?
(11 answers)
Closed 8 years ago.
I have a code below that asks if the user wants to retry or not. If the user enters no, the program will terminate. My code doesn't work and the loop still runs even if the input is "no"
#include<stdio.h>
int main()
{
char x[5];
do
{
printf("would you like to try again?");
scanf("%s",&x);
}
while(x != "no");
getch(); return 0;
}
I've tried adding a space in the scanf just like for characters to consume the newline but it also doesn't work. sorry for a very noob question.
You should use strcmp() to compare strings.
do { ... } while (strcmp(x, "no") != 0);
The issue of comparing an char array has been addressed by other answers and comments. There is another possible problem with an array of 5 elements being overrun by an input of "Yes, I would like to try again." Using %4s will limit scanf. Another option would be to use fgets ( x, sizeof ( x), stdin); fgets will include the newline so the comparison would be to "no\n" instead of "no".
#include<stdio.h>
#include<string.h>
int main()
{
char x[5];
do
{
printf("would you like to try again?");
scanf("%4s",x); // %4s prevent overrun. x is array, no need for &
}
while( strcmp ( x, "no") != 0);
getchar();
return 0;
}
You can't compare two strings by using !=, since the value of x is actually the memory address of your string.
You must include string.h and use the strcmp() function. (Take a look at the doc.)
x is just stand for the base address of the array while "no" is just stand for the address of the literal string [no\0]. So x != "no" is comparing two addresses which is always false.
You should use strcmp in the standard C lib.
Your problem is at the condition of the while loop. x is an array that contains characters. Using the x!="no" you are checking the base address of the array (to be more specific when you drop the brackets the compiler translate that as a pointer that points at the array x at the cell x[0,0]).
So the best solution and the easiest one to your problem is to use the strcmp function. The strcmp stands for string compare. This function compares character by character between two strings using the ascii code. The strcmp function returns zero only if the two strings are the same.So at your case you should use something like:
while(strcmp(x,"no")!=0){
....

Resources