Compare Strings in C [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 8 years ago.
OMG, I know this should be extremely simple and I have tried everything I have researched but nothing works. I am missing something simple, please help. I just want to declare a string and then later compare it to another string.
I want to declare a key of something like 9 characters. Then I want to compare this string to another one submitted later. Below is what I have and no matter what I change I get errors from incompatible types to missing token.
char key[] ="kjherres";
char f[];
F="kjherres";
if (key==f) {
//run my code
}
I have also tried (strcmp) to no avail. What am I missing? Please help.

The way you compare strings is with the strcmp function.
if ( strcmp(key,f) == 0 ) {
/* strings are the same */
}
You should have a good book or online tutorial to learning C. If you're coming from PHP or some other high-level language, you have a LOT to learn and if you don't do it right, you're asking for big problems. Strings are not as trivial in C as they are in PHP etc.
Also, C is case-sensitive. F and f are different names.

OK, this was a stupid thing I missed as always. Sometimes my mind is going faster than my fingers.
What the problem was is that I assigned f from a url param but I was only reading the first char of the param. Forgive me for the ignorance, it can happen often when going too fast.

Related

Init fixed size float array in C [duplicate]

This question already has answers here:
Array initialization C
(5 answers)
Closed 1 year ago.
I noticed a piece of code that made me raise a few eyebrows in the code base which I am working on.
Since I am not an expert of the C language, I first tried googling initializing fixed size arrays.
However, I could not find anything like that:
float array[7] = {0.0,};
To be precise, I would like to know how the comma is interpreted in C here? I doubt it is a typing error, because I find this kind of initialization all over the place and for all types of arrays.
Is there any difference to just writing:
float array[7] = {0.0};
This has nothing to do with floats. It goes for all arrays. Imagine that that rule did not exist and you you have this:
float arr[] = {
4.5,
2.3,
3.8
};
Later, you realize that you want to remove 3.8. Then you would ALSO need to remove the comma after 2.3. And the same thing goes if you want to insert a new value. Let's say that you have copied a value from somewhere. Now you cannot simply paste it. Because if the copied string has a comma, you could not simply paste it anywhere you want in the array.
The basic purpose is that you should not have to think about adding and removing commas. It's just convenience.
Imagine copying and pasting regular code and you would have to think about that for the semicolon everytime. That would be a bit annoying. That's how it is in Pascal. ;)

'If' Condition Not Working As Expected In My C Code

I am fully aware that this is due to some error overlooked by me while writing my text-based calculator project in C, but I have only started learning C less than a week ago, so please help me out!
Since the entire code is 119 lines, I'll just post the necessary snippet where the real issue lies: (There are no errors during compiling, so there is no error beyond these lines)
char choice[15];
printf("Type 'CALCULATE' or 'FACTORISE' or 'AVERAGE' to choose function :\n");
gets(choice);
if (choice == "CALCULATE")
The bug is that even after perfectly entering CALCULATE or FACTORISE or AVERAGE, I still get the error message that I programmed in case of invalid input (i.e, if none of these 3 inputs are entered). It SHOULD be going on to ask me the first number I wish to operate on, as written for the CALCULATE input.
The code runs fine, no errors in VS 2013, and so I'm sure its not a syntax error but rather something stupid I've done in these few lines.
If you use == you are comparing the addresses of 2 arrays, not the contents of the arrays.
Instead, you need to do:
if (strcmp(choice, "CALCULATE") == 0)
Two things to mention here:
Never use gets() it has serious security issues and is removed from the latest standard. Use fgets() instead.
To compare strings, you should use strcmp(), not ==.
The problem is you're trying to compare a string literal with a char array. C isn't found those things being the same, since the '==' comparison operator is not implemented in that way.
You have two options for performing that comparison :
1) Use the strcmp() function, from string.h library
2) Manually comparing the chars in your array, and the string literal
Definitely, the first option is the easiest and cleanest one.

C: How can I cast a pointer (or am I going about this all wrong)? [duplicate]

This question already has answers here:
Creating an atoi function
(5 answers)
atoi implementation in C
(6 answers)
Closed 4 years ago.
I should first start out by saying that I come from a Java background. That being said, I'm just starting to learn C and I really struggle with the use of pointers. The concepts are simple enough, but actually using them proves to be a rather difficult and frustrating experience for me.
At any rate, I'm trying to create a function that replicates atoi without using the stdlib.h library. I'm thinking it's a simple matter of casting, but when I test it I get some really strange results. What I have is as follows:
int myatoi(const char* str){
return (int)*str;
}
Given that I don't really know what I'm doing when it comes to pointers, I'm most certainly doing something wrong, but I have absolutely no idea what.
That will not work. Casting will result in the "reinterpretation" of the first character (at location *str) into its ASCII value as an integer.
You will need to process the string by iterating through its characters and parsing them.

generating new variables in c [duplicate]

This question already has an answer here:
Creating variable names from parameters
(1 answer)
Closed 8 years ago.
Is is possible for your code to generate new variables in c? For example, if I made "example_variable = 15", is there any way to automatically generate 15 new variables such as: "generated_variable_1", "generated_variable_2", "generated_variable_3", all the way to "generated_variable_15"?
I'm very new to c, and I haven't had a proper introduction to it, so I only know the basics, especially when it comes to variables. I am pretty sure this is really high-level stuff, so I'm sorry if the question doesn't make sense. I am open to any suggestions for alternate ways of generating the variables.
I know there are probably answers already out there, but I've had trouble finding them and would like answers specific to what I'm looking for, as opposed to piecing together what I need from what I can find.
What you are talking about - generating variables at runtime - is not possible in C. The reason is that C is a low-level language and does not expose an API for runtime manipulation. In fact, once compiled, C programs don't use variables - are values are stored directly in memory using memory addresses.
The closet equivalent to what you're looking for that's available in C is an "array". To declare an array, you can do:
int var[15];
int var2[n]; // in C99+, n is a variable saying how many elements you want in the array
You can also do this with malloc, but this is a bit more complicated and then you must free the values.
A running C program doesn't use your variable names at all. Those names were useful for the compiler to build the program, but are discarded before you run it. This means that in C (but not in interpreted languages like python):
If you rename your variables, you get the exact same program
If you do strings <your program> you won't see any variable names (unless you retained debugging symbols)
Hence, runtime is too late to create new variables. In C, variables are compile-time only. Of course, you can use arrays, or dictionaries, to simulate run-time variable creation, like the other answer, and a few commenters, suggest.

How give array name from string variable in C [duplicate]

This question already has answers here:
Variable with char[] name
(3 answers)
Closed 8 years ago.
I am stuck with a situation where I need to give array name from string variable.
Basically I want to create an array with same name as value in another string variable "name":
char *name="arr_name";
In my case the string being hold by variable name may change. Hence advice accroding.
Thanks!
I think you're looking for some mechanism, similar to the ones found in the higher level languages as in python (introspection), or C# (reflections). C doesn't provide this kind of insight from the runtime, not even the variable names are existing in the bytecode - so basically it's not possible and doesn't make any sense in the terms of the way how C works.
I don't know if that helps, but one thing you could do is to statically (so in the compilation time, not while it's running!) populate char* and create variable with the same name, given that the value of the string is a proper name for the variable (Naming convention for C/C++). You can achieve that by defining a proper macro (#define your_macro(...) code_to_populate_char_and_declare_variable), but I cannot see any point in doing so.

Resources