How to input and compare a string [duplicate] - c

This question already has answers here:
scanf and strcmp with c string
(3 answers)
Closed 6 years ago.
I'm new to C and I need help.
This code doesn't work, even if I type London into the input I recieve the message from else: "Try again".
int main()
{
char capitalCity;
scanf("%s", &capitalCity);
if (capitalCity == 'London'){
printf("Is the capital city of UK.");
}
else{
printf("Try again.");
}
return 0;
}

There is no string data type in C programming language. Strings in C are represented as array of characters.
In C, char is a data type to represent a character (char in C represents the character type, suitable for storing a simple character—traditionally one from the ASCII encoding.). So, all you need to do is declare a array of char data type to represent a string in C. Each element in that array will hold a character of your string.
Also, operators in C like ==, !=, +=, + are defined for build-in data types in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.
Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0') which marks the end of the string.
The Header file has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.
So, your program should look like:
#define MAX_CSTR_LEN 100
int main()
{
char capitalCity[MAX_CSTR_LEN + 1]; ///An extra position to store Null Character if 100 characters are to be stored in it.
scanf("%s", capitalCity);
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if (strcmp(capitalCity, "London") == 0) {
printf("Is the capital city of UK.");
}
else {
printf("Try again.");
}
return 0;
}
Also, you have to use single quotes for character literals and double quotes for strings in C.

First, there are many things you need to learn. I'm trying my best to explain it to you.
In case of string as input, you can't compare by using == operator. you need to use strcmp() function which is declared in <string.h> header file, it compares character by character and return 0 if both string equal else a non-zero value.
#include <stdio.h>
#include <string.h> //for strcmp function
#define SIZE 30 //max size buffer for input
int main(){
char capitalCity[SIZE];
scanf("%s", capitalCity);
if(strcmp(capitalCity, "London") == 0){ //if(capitalCity == 'London') won't work in case of string comparison
printf("Is the capital city of UK.");
} else{
printf("Try again.");
}
return 0;
}
further reading http://www.geeksforgeeks.org/c/

Related

How on earth to use char and if statements?

I'm a rookie programmer trying to run a simple code on VS code.
#include<stdio.h>
int main()
{
char* a;
printf("Enter a char");
scanf("%s",&a);
if (a = "yes")
{
printf("Number is 30");
}
else if (a = "no")
{
printf("Number is 50");
}
else{
printf("oops");
}
return 0;
}
I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no".
The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.
If possible, please explain me how to use char,strings,arrays with if-else statements.
There are several misunderstandings in the posted code.
First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So
'y' is a char
"yes" is a string
You print "Enter a char" but from the code it's obvious that you really want "Enter a string".
This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:
char a[10]; // Make it an array of char so that it can hold a string
printf("Enter a string, max 9 characters");
scanf("%9s", a); // No & before a and width specifier used to avoid buffer overflow
Now this part
if (a = "yes")
is not the way to compare two strings in C. For that you need the function strcmp - like:
if (strcmp(a, "yes") == 0)
Putting it together it's like:
int main()
{
char a[10];
printf("Enter a string, max 9 characters");
scanf("%9s", a);
if (strcmp(a, "yes") == 0){
printf("Number is 30");
}
else if (strcmp(a, "no") == 0)
{
printf("Number is 50");
}
else
{
printf("oops");
}
return 0;
}
That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.
note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.
There are different ways to initialize a variable to access C string.
char *char_ptr = "Hello";
This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.
A more convenient way to define strings that can be modified is to use:
char str[];
This way you can modify any character in the C string
p.s you also need to use strcmp() for the if statement
You can take string input in C using
scanf(“%s”, str);
And to compare the string you need to use:
strcmp(str1, "yes");

Scanf for a word in C language

Hey I got this code where I need to scanf the input of the user (ANO/NE) and store this input into variable "odpoved". How to do that? What I have now looks like it is scanning just the first letter of the input.
char odpoved;
printf("Je vše v pořádku? (ANO/NE)");
scanf("%s", &odpoved);
if(odpoved == "ANO" || odpoved == "ano"){
printf("Super, díky mockrát");
}
else if(odpoved == "NE" || odpoved == "ne"){
printf("To mě mrzí, ale ani já nejsem dokonalý");
}
else{
printf("Promiň, ale zmátl jsi mě. Takovou odpověď neznám!!!");
return 0;
}
The first thing you should know about is that char is a data type consisting of 1 byte and is used to store a single character such as 'a', 'b', 1, 2 etc... there are 256 possible characters which are often represented by the ASCII table ( https://www.ascii-code.com/).
As odpoved is a string you need to make it type char* or equivalently char [] which is a pointer to the first char in the array (string) of characters. The last char in a string is always a terminator byte '\0' used to indicate the end of a string. The null terminator is automatically inserted when the speech marks are used e.g. "sometext" or when %s is used to get input.
The other mistake you have made is to compare strings with == or != signs. This will not work as the first characters will be compared with each other. Hence to compare the characters you will need to use strcmp function provided when the string.h library is included. There are many other useful string functions such as strlen which tell you the length of the string etc.

How can I debug this basic OR program?

I am a beginner in C programming.
I have written a program which is not functioning due to its 'OR' functionality. Here is a working code snippet:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* englishTest = 'yup';
if ( (englishTest == 'yup') || (englishTest == 'yep') || (englishTest == 'yas') || (englishTest == 'yah') )
{
printf("You may pass \n");
}
else
{
printf("You shall not pass \n");
}
return 0;
}
This is supposed to be C, not a scripting language.
There are two problems in this code:
char englishTest = 'yup';
englishTest is declared as char which in C is an integer type. It can hold only one character but you attempt to store three characters in it.
What you probably meant is:
char englishTest[] = "yup";
Please note the square brackets that denote an array (of chars). The array size can be optionally specified between the brackets. It is not specified here and the compiler uses the smallest value that can hold the string used for initialization ("yup"). This smallest value is 4: there are 3 characters in "yup" but C strings are terminated with the NULL character ('\0').
The second issue in your code is the comparison of strings. The strings are not primitive types in C. They are arrays of characters. Directly comparing two strings using the comparison operators doesn't produce the result you expect. It compares the addresses in memory where the two strings are stored, not their characters.
The C standard library provides several functions to compare two strings. The most straightforward string comparison function is strcmp(). It returns 0 if the two strings are identical, a negative value if the first string comes before the second string in the dictionary order or a negative value otherwise.
Your comparison code should be (note the C strings are enclosed in double quotes ""):
if (strcmp(englishTest, "yup") == 0 || strcmp(englishTest, "yep") == 0 ||
strcmp(englishTest, "yas") == 0 || strcmp(englishTest, "yah") == 0)
P.S. The OR operators (||) do not break anything here.

Checking equality of a string in C and printing an answer [duplicate]

This question already has answers here:
C Strings Comparison with Equal Sign
(5 answers)
Closed 9 years ago.
i've written some simple code as an SSCCE, I'm trying to check if string entered is equal to a string i've defined in a char pointer array, so it should point to the string and give me a result. I'm not getting any warnings or errors but I'm just not getting any result (either "true" or "false")
is there something else being scanned with the scanf? a termination symbol or something? i'm just not able to get it to print out either true or false
code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 20
//typedef char boolean;
int main(void)
{
const char *temp[1];
temp[0] = "true\0";
temp[1] = "false\0";
char var[LENGTH];
printf("Enter either true or false.\n");
scanf("%s", var);
if(var == temp[0]) //compare contents of array
{
printf("\ntrue\n");
}
else if(var == temp[1]) //compare contents of array
{
printf("\nfalse\n");
}
}
const char *temp[1];
This defines tmp an array that can store 1 char* element.
temp[0] = "true\0";
Assigngs to the first element. This is okay.
temp[1] = "false\0";
Would assign to the second element, but temp can only store one. C doesn't check array boundaries for you.
Also not that you don't have to specify the terminating '\0' explicitly in string literals, so just "true" and "false" are sufficient.
if(var == temp[0])
This compares only the pointer values ("where the strings are stored"), not the contents. You need the strcmp() function (and read carefully, the returned value for equal strings might not be what you expect it to be).
Use strcmp for comparing strings:
#include <stdio.h>
int main(void)
{
const int LENGTH = 20;
char str[LENGTH];
printf("Type \"true\" or \"false\:\n");
if (scanf("%19s", str) != 1) {
printf("scanf failed.");
return -1;
}
if(strcmp(str, "true") == 0) {
printf("\"true\" has been typed.\n");
}
else if(strcmp(str, "false") == 0) {
printf("\"false\" has been typed.\n");
}
return 0;
}
and also note that:
string literals automatically contain null-terminating character ("true", not "true\0")
const int LENGTH is better than #define LENGTH since type safety comes with it
"%19s" ensures that no more than 19 characters (+ \0) will be stored in str
typedef char boolean; is not a good idea
unlikely, but still: scanf doesn't have to succeed
and there is no #include <iostream> in c :)
== checks for equality. Let's see what you're comparing.
The variable var is declared as a character array, so the expression var is really equivalent to &var[0] (the address of the first character in the var array).
Similarly, temp[0] is equivalent to &temp[0][0] (the address of the first character in the temp[0] array).
These addresses are obviously different (otherwise writing var would automatically write temp[0] as well), so == will always return 0 for your case.
strcmp, on the other hand, does not check for equality of its inputs, but for character-by-character equality of the arrays pointed to by its inputs (that is, it compares their members, not their addresses) and so you can use that for strings in C. It's worth noting that strcmp returns 0 (false) if the strings are equal.

Begginger, string in switch in C with sourcecode. Possible?

So basically I wanted to create a program in C, in wich you would input 2 character long string (mix of letter and noumber ex.r1,u2,i3,i4,r6) to be the input in my program. Later I want to put this string in SWITCH. Is this possible?
Here's my simple sourcecode. Please correct me on any mistakes :)
#include <stdio.h>
int main(void)
{
char string[2];
scanf("%s", &string);
switch (string)
{
case 'u1' :printf("%s\n", string);break;
default :printf("ERROR");break;
}
return 0;
}
Create a code based on the string and switch on that.
#define Code(a,b) (a + 256*b)
char string[3]; // 3 not 2
if (scanf("%2s", string) != 1) { // No &
Handle_Error();
}
int scode = Code(string[0], string[1]);
switch (scode) {
case Code('u', '1') : printf("%s\n", string); break;
case Code('r', '2') : printf("r2\n"); break;
...
default :printf("ERROR");break;
}
A switch(x) needs an integer value for x and string is an array. So the original approach will not work.
The program can use an integer based on the string for x and use the same method for generating the case values. Since there is only the first 2 char of the string are of interest, the int value is unique.
No, this is not possible. Switch only works with integral types in C (int, short, long, etc, as well as types defined with enum).
You can however use a simple if-else construct to get the same behavior:
if (strcmp(string, "ui" ) == 0) //test for string equality
{
printf("%s\n", string);
}
else
{
printf("ERROR")
}
We use strcmp instead of == because we are dealing pointers which almost certainly not compare equal even when the two strings have the same content.
strcmp(str1, str2) == 0 is the standard idoim in C for comparing two strings.
strcmp returns an integer representing how two strings compare to each other. 0 means they are equal, a negative number means that the first string is lexographically "less than" the second, and a positive number means that the first string is lexographically "greater than" the second. More info can be found here.
A switch won't work here.
You need to use an if/else if construct and strcmp to compare the strings.
Also, you need at least 3 characters in your input array so that it can hold the two input characters and the terminating null character.
Of course, such a small buffer can easily overflow.

Resources