Here is the problem. I need to compare two strings in C language.
What i have is a program reading in data from a file. i read in information in the form fscanf(file,"%s",%26amp;last);
if(d.filed==last)
{ execute whats in here)
else if(d.filed==first)
{execute here}
Note that in the struct defined as struct test, lets say d.filed was " Mike". when i read in from the file, for some reason last does not receive the value "Mike" because i try to print and i receive some weird character. i defined last as being ** Char last,first;
Comparing 2 strings in C?
It's nice to have the whole program so we know how much to explain. For example, fscanf will read in characters until it reaches a whitespace character or NULL, then writes a null into the target string. If d.filed has any whitespace characters in it, the strings won't be equal.
Second, for manipulating strings you want the string.h (usually) or ctype.h (occasionally) header files. In this case you want the function int strcmp(char *, char*) from string.h. It returns 0 if the two strings are equal.
I would write it as if (!strcmp((d.filed), last){
.
.
.
}
else
{
.
.
.
}
but since I don't have the programs I don't know whether you need the second test.
A word about my sources: C++ has been described by its creator as C with classes and namespaces. cplusplus.com is an excellent site for documentation of both C and C++, however it obviously focuses on the latter. When they incorporated the standard template library into C++ they renamed all the standard c headers, so stdio.h became cstdio, stdlib.h became cstlib and of course string.h became cstring. In C++. In C they remain what they always were. Or as my GCC cstring header says:
/** @file cstring
* This is a Standard C++ Library file. You should @c #include this file
* in your programs, rather than any of the "*.h" implementation files.
*
* This is the C++ version of the Standard C Library header @c string.h,
* and its contents are (mostly) the same as that header, but are all
* contained in the namespace @c std (except for names which are defined
* as macros in C).
*/
C doesn't have namespaces. Thus you can learn what you need about C functions at C++, but you have to look elsewhere than you would in a C programming site. That's why I'm going to list the links to the page where I got some information after it.
Reply:use strcmp().
#include %26lt;string.h%26gt;
int strcmp(const char *s1, const char *s2);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment