-
help with strings
Hey all. I'm writing a program involving strings. I can get the user to input the information, however, I am getting stuck when trying to test the user's information.
I want to know why I can't perform the bolded code? I want to test if the color the user input is equal to the color I type in "quotes".
Code:
char color1[STRING],
color2[STRING],
color3[STRING];
char holder;
int a, b, c;
printf("Enter the colors of the resistor's three bands, beginning with\nthe band nearest the end. Type the colors in lowercase letters\nonly, NO CAPS.\nBand 1 => ");
scanf("%s", color1);
printf("\nBand 2 => ");
scanf("%s", color2);
printf("\nBand 3=> ");
scanf("%s", color3);
if (color1 = "black")
a = 1;
if (color1 = "brown")
a = 2;
printf("\n%f", &a);
return (0);
}
-
1 - You're using = which is the assignment operator, not == which is used for equality testing.
2 - You can't compare strings in C using ==, you have to use some of the string functions (or write your own), such as strcmp.
3 - %f is for floating point numbers, not integers.
4 - &variable is the address of a variable, which is not what you're trying to print.
Quzah.
-
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char s[100], *p;
printf("\nEnter your password: ");
fgets(s, sizeof(s), stdin);
if((p=&s[strlen(s)-1]) == '\n') *(p-1) = 0;
if(strcmp(p, "thepassword") == 0) {
printf("\nPass");
}
else {
printf("\nWrong password");
}
return 0;
}
-
Code:
if((p=&s[strlen(s)-1]) == '\n') *(p-1) = 0;
Don't you mean *p = 0;?
-
Yes, I just realized I'd already subtracted 1.