#include <stdio.h>
#include <conio.h>
#include <string.h>
main() {
char d[10];
int value = 0, val1, val2;
printf("Enter Day: ");
scanf("%c", &d);
val1 = strcmp(d, "sunday");
val2 = strcmp(d, "saturday");
if (val1 == 0) {
printf("AS");
value = 2;
} else
if (val2 == 0) {
value = 1;
}
switch (value) {
case 2:
printf("So sad, you will have to work");
break;
case 1:
printf("Enjoy! its holiday");
break;
default:
printf("Print valid character");
}
}
I enter code here want to input days and to get some output using switch statement but strcmp is not working in if statement
I have to use a switch statement also
if statement not recognising value.
At least this problem:
strcmp(d,"sunday") expects array d to contain a string.
d does not certainly contain a string as no null character was assigned there.
char d[10];
printf("Enter Day: ");
scanf("%c",&d); // Writes, at most, 1 character to `d`. Remainder of `d[]` is uninitialized.
Instead
if (scanf("%9s",d) == 1) {
printf("Success, read <%s>\n", d);
Tip: Consider using fgets() to read user input.
Tip: Enable all compiler warnings to save time.
Related
I have this code and it keeps adding what ever the guesses string is to the wordle string when I compare them, resulting in them to never be the same. How can I fix this?
#include <string.h>
int main() {
char wordle[5];
char guesses[5];
int guess = 5;
int value;
printf("Please input a secret 5 letter word:\n");
scanf("%s",wordle);
while (guess != 0){
printf("You have %d tries, please guess the word\n",guess);
scanf("%s",guesses);
value = strcmp(wordle,guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}```
Your program has undefined behavior. You're making two mistakes.
If your user enters 5 characters, it takes 6 characters to store the string. The program would attempt to write a null terminator into wordle[5] which is not a valid index.
Your user could enter any number of letters. You need to make sure they don't overflow your buffer.
#include <stdio.h>
#include <string.h>
int main() {
char wordle[6];
char guesses[6];
int guess = 5;
int value;
int chars_read;
do {
printf("Please input a secret 5 letter word:\n");
chars_read = scanf("%5s%*s\n", wordle);
} while(chars_read != 1 && strlen(wordle) != 5);
while (guess != 0){
do {
printf("You have %d tries, please guess the word\n", guess);
chars_read = scanf("%5s%*s\n", guesses);
} while(chars_read != 1 && strlen(wordle) != 5);
value = strcmp(wordle, guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}
See it in action
scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
MSC24-C. Do not use deprecated or obsolescent functions
Your strings for wordle and guesses are too short. You need to make room for '\0'. They should be 6 bytes long not 5.
char wordle[6];
char guesses[6];
I am trying to get 4 integers from an IP-address. For example, 12.34.56.78. A = 12, b = 34, c = 56, and d = 78. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ADDRESS[100];
printf("Enter IP: ");
scanf("%s", ADDRESS);
return 0;
}
How would I be able to do this?
try to use good old sscanf().
int A, B, C, D;
sscanf(ADDRESS, "%d.%d.%d.%d", &A, &B, &C, &D);
It may be a good idea to check if sscanf() returned 4 what indicates that all four numbers were correctly parsed.
if you're asked to read it as a string at first , you need to add a condition that it exists 4 points in the string
do {
count=0;
for (i=0;i<strlen(address);i++) {
if (address[i] == '.')
count++;
}
if (count > 4) {
printf("Enter IP: ");
scanf("%s", ADDRESS); }
while (!(count <= 4));
secondly using strtok can make everything easy , you have to split your string with the . caracter so it goes with something like this
char *tester;
int counter=0,a,b,c,d;
tester = strtok(address, ".");
while( tester != NULL ) {
switch (counter) {
case 0:
a=atoi(tester);
counter++;
break;
case 1:
b=atoi(tester);
counter++;
break;
case 2 :
c=atoi(tester);
counter++;
break;
case 3:
d=atoi(tester);
counter++;
break; }
tester= strtok(NULL, ".");
}
The program will prompt the user to enter a simple expression. After splitting the string and assigning the variables, i want to check to see if what the user entered is a an integer so it can be calculated in the switch statement. What would be the best way to validate the data inside num1 and num2 to make sure they are integers and not letters or any other character.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*This function will display the user's desired expression to be calculated */
char* expressionDisplay(char* input)
{
char *str = input;
printf("The expression entered is: %s\n", str);
}
int main()
{
char str[50];
char operator[6] = "+-*/%";
int num1,num2;
char calculation;
char *oldstr = malloc(sizeof(str));
printf("This program will solve a simple expression in the format 'value' 'operator' 'value'\n ");
printf("Example 2+6 or 99 * 333\n");
printf("Enter the simple expression to be calculated: \n");
scanf("%[^\n]%*c", str); //this will scan the whole string, including white spaces
strcpy(oldstr, str);
for(int i = 0; i < strlen(operator); i++)
{
char *position_ptr = strchr(str, operator[i]);
int position = (position_ptr == NULL ? -1 : position_ptr - str);
if(str[position] == operator[i])
{
calculation = operator[i];
char *num1_ptr = strtok(str, operator);
int num1 = atoi(num1_ptr);
char * num2_ptr = strtok(NULL, operator);
int num2 = atoi(num2_ptr);
break;
}else
calculation = position;
}
switch(calculation)
{
case '+':
expressionDisplay(oldstr);
printf("Sum\n");
break;
case '-':
expressionDisplay(oldstr);
printf("Subtract\n");
break;
case '*':
expressionDisplay(oldstr);
printf("Multiply\n");
break;
case '/':
expressionDisplay(oldstr);
printf("Division\n");
break;
case '%':
expressionDisplay(oldstr);
printf("Modulus\n");
break;
default:
printf("Sorry unable to calculate the expression entered. Try again.\n");
printf("Enter a simple expression - number operator number - ");
break;
}
}
In this case you can use the strtol function of standard c library.
You can see more detail about it at this link : strtol - c++reference.
I'm learning C and I'm having trouble with this situation where I need to put values inside a matrix based on user char input, here is the code:
#include <stdlib.h>
#include <stdio.h>
int main() {
int mat[2][2] = { NULL };
char sex;
printf("Insert gender (m or f):");
scanf_s("%c", &sex);
if (&sex == "m") {
mat[0][0] = 1;
}
if (&sex == "f") {
mat[0][0] = 2;
}
else{
mat[0][0] = 3;
printf("invalid\n");
}
printf("inserted: %c \n", sex);
printf("value on matrix 00: %i\t", mat[0][0]);
//printf("%i\n", mat[0][1]);
//printf("%i\t", mat[1][0]);
//printf("%i", mat[1][1]);
return 0;
}
The values at the end seem to be right but the program don't runs as I expected and I can't see my mistake, any help?
In C, operator == cannot be used to compare strings. To do so, you should use the function strcmp from string.h. In any case, what you need is not to compare strings, but to compare characters (and what you are doing is to compare an address with a string). My suggestion: scan a char instead of a string (using scanf instead of scanf_s) and change your equality tests from &var == "val" to var == 'val'. Also some tips in the code below:
#include <stdlib.h>
#include <stdio.h>
int main()
{
//name your variables properly
//initialize them immediately to avoid undefined values
//respect its types: use '\0' instead of 0 for chars, and 0 instead of NULL for ints
char gender = '\0';
int matrix[2][2] = {{0, 0}, {0, 0}};
//display accurate messages to the user
printf("Select a gender (m or f): ");
//don't scan a string if you only need a char
//always check the return of a scan
if(scanf("%c", &gender) <= 0)
{
printf("Input error\n");
return 0;
}
//switch is usually more efficient than else-ifs
switch(gender)
{
case 'm':
matrix[0][0] = 1;
break;
case 'f':
matrix[0][0] = 2;
break;
default:
printf("Invalid gender\n");
return 0;
}
printf("Selected gender: %c\n", gender);
printf("Value on matrix[0][0]: %d\n", matrix[0][0]);
return 0;
}
&sex == "m" compares the address of sex with the address of the string literal "m", which will presumably evaluate to false. This is not what you want.
You should compare the value of sex with the character literal 'm', as in:
if (&sex == "m") {
// ...
}
The same goes for &sex == "f", which should be sex == 'f'.
So my code does the following:
Ask what's the option
If option is 1: Scan some numbers
If option is 2: Print those numbers
After each option, ask if user wanted to continue choosing (Y/N)
This is my main code
while(yesnocheck==1)
{
printf("What's your option?: ");
scanf("%d",&b);
switch(b){
case 1:
printf("How many numbers?: ");
scanf(" %d",&n);
a=(struct sv*)malloc(n*sizeof(struct sv));
for(int i=0;i<n;i++)
scanf("%d",&((a+i)->num));
break;
case 2:
for(int i=0;i<n;i++)
printf("%d\n",(a+i)->num);
break;
}
yesnocheck==yesnochecker();
}
And this is the yesnochecker function:
int yesnochecker()
{
char yesorno;
printf("Do you want to continue? (Y/N)");
while(scanf("%s",&yesorno))
{
if(yesorno=='Y')
return 1;
if(yesorno='N')
return 0;
printf("*Wrong input. Please reenter (Y/N): ");
}
}
So on dev C++, my code won't run correctly. After it's done option 1, when I enter "Y" then choose option 2, case 2 will display some weird numbers. However it works well on online C compilers.
And then, when I change the char yesorno in yesnochecker() function to char yesorno[2] and treat it as a string, the code does work.
Can someone shed some light?
It is a bad idea to read a char c with scanf("%s", &c);. "%s" requires a buffer to store a string. The only string which fits into a char is an empty string (consisting only of a terminator '\0' – not very useful). Every string with 1 character requires 2 chars of storage – 1 for the character, 1 for the terminator ('\0'). Providing a char for storage is Undefined Behavior.
So, the first hint was to use the proper formatter instead – "%c".
This is better as it removes the Undefined Behavior. However, it doesn't solve another problem as the following sample shows:
#include <stdio.h>
int cont()
{
char c; do {
printf("Continue (y/n): ");
scanf("%c", &c);
printf("Input %c\n", c);
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main()
{
int i = 0;
do {
printf("Loop iteration %d.\n", ++i);
} while (cont());
/* done */
return 0;
}
Output:
Loop iteration 1.
Continue (y/n): y↵
Input 'y'
Loop iteration 2.
Continue (y/n):
Input '
'
Continue (y/n): n↵
Input 'n'
Live Demo on ideone
WTH?
The scanf("%c") consumes one character from input. The other character (inserted for the ENTER key) stays in input buffer until next call of any input function.
Too bad, without ENTER it is hard to confirm input on console.
A possible solution is to read characters until the ENTER key is received (or input fails for any reasons). (And, btw., getc() or fgetc() can be used as well to read a single character.):
#include <stdio.h>
int cont()
{
int c;
do {
int d;
printf("Continue (y/n): ");
if ((c = fgetc(stdin)) < 0) {
fprintf(stderr, "Input failed!\n"); return 0;
}
printf("Input '%c'\n", c);
for (d = c; d != '\n';) {
if ((d = fgetc(stdin)) < 0) {
fprintf(stderr, "Input failed!\n"); return 0;
}
}
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main()
{
int i = 0;
do {
printf("Loop iteration %d.\n", ++i);
} while (cont());
/* done */
return 0;
}
Output:
Loop iteration 1.
Continue (y/n): y↵
Input 'y'
Loop iteration 2.
Continue (y/n): Hello↵
Input 'H'
Continue (y/n): n↵
Input 'n'
Live Demo on ideone
Please, note, that I changed the type for the read character to int. This is because getc()/fgetc() return an int which is capable to store any of the 256 possible char values as well as -1 which is returned in case of failing.
However, it isn't any problem to compare an int with a character constant (e.g. 'y'). In C, the type of character constants is just int (SO: Type of character constant).