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.
Related
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");
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.
I want to make a stock calculator with C language, and it still in progress. I make it using Microsoft Visual Studio 2015.
When I input a string(example: "refrigerator") and I print it using printf, my computer can print it. But when that string put into an if it can't continue. The progress stop at:
scanf_s("%s",stock1,sizeof(stock1));
fflush(stdin);
After that when I input "refrigerator" the if statement is not coming out.
Here is my code:
int fan, refrigerator, lpg;
int menu;
char stock1[15], stock2[15];
int total1, total2, totalstock;
int check;
printf("Type the item that you want to add\n");
scanf_s("%s",stock1, sizeof(stock1));
fflush(stdin);
if (stock1 == "refrigerator")
{
printf("How many item would you like to add?\n");
scanf_s("%d", &total1);
fflush(stdin);
}
getchar();
return 0;
}
In C you should use the strcmp function to compare strings. For example, in your case you'd compare your string to "refrigerator" in the following manner:
if(strcmp(stock1, "refrigerator") == 0)
{
/* etc */
}
There are quite a few string functions available - you should probably familiarize yourself with them.
Best of luck.
Your problem is you are comparing a string literal with a char array that the wrong way of comparing string literals with a char array you must use
if(strcmp(stock,"refrigerator")==0)
instead of
stock1=="refrigerator"
strcmp return 0 if the string 1 is identical to string 2, >0 if string 1 is greater than string 2 and <0 if string1 is less than string2.
Since you're using C language, you must use strcmp function.
strcmp function returns 0 value if both strings have the same value.
Use it this way:
if(strcmp(string,"refrigerator") == 0)
{
/*string is equal to "refrigerator"*/
} else {
/*string is not equal to "refrigerator"*/
}
Don't forget to include string.h
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/
I would like to ask how to identify a sequence in C for example AAAAA & ddddd the sequence is all of the inputted characters must be the same.. How is it possible to achieve that? Do I need to use char ? Here is what i had try
#include<stdio.h>
int main() {
char ch;
scanf("%cccc", &ch);
if (ch = 'c')
printf(&ch);
else
printf("Character is Not the same sequence");
return (0);
}
To compare two characters:
char a = 'a';
char b = 'b';
return a == b; // this compares integer values of two characters
// and returns 1/0 if they do match/do not match
To compare strings:
char str1 = "AAAAA";
char str2 = "aaaaa";
return strcmp(str1, str2);
man strcmp(3):
The strcmp() function compares the two strings s1 and s2. It returns
an integer less than, equal
to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater
than s2.
The strncmp() function is similar, except it compares the only first (at most) n bytes of s1 and
s2.
Your code contains few bugs. %c format is for scanning single character, use %s for strings. Here:
if (ch = 'c')
you assigned 'c' to ch, not what you wanted. Use == in C for comparisons.
I would try this:
Accept a string as input (instead of a character)
Set up a loop to walk through the string, character by character
Your first character will be the "good" value
If at any time, you encounter a different character, fail out of the loop
If you reach the end of the string without failing, you succeed
Create a Macro for the pattern you want to find. typecast your input to the size of the pattern you want to recognise. Subtract both. If 0 pattern matched. Else,shift right 1 bit and repeat. Example, Pattern to find #define wPAT 0x1234. Input=> U32 dwInput=0x12345678. Result= (U16)dwInput - wPAT . If 0,pattern found. Else, dwInput>>1 and repeat Result= (U16)dwInput - wPAT. Repeat 16 times to find if pattern is present or not