Skip to main content
GameDev.net gamedev.net
🔒 Locked

comparing strings and chars

Started by Drakon Feb 29, 2004 at 5:33 PM 4 replies 400+ views
Original Post
Drakon
Drakon
How would I compare a string from gets() with another?
"Go for the eyes, Boo, go for the eyes!"
dcosborn
dcosborn
C:
#include <string.h>
int strcmp(const char *string1, const char *string2);

C++:
#include <cstring>
int std::strcmp(const char *string1, const char *string2);

If the returned integer is zero, they''re the same.
Drakon
Drakon
Thanks, it works.

Also, how would I go about making one input by gets(string) split into two different strings seperated by spaces?

example, if I type in ''info 12'' , how could I get the info to be one string, and the twelve as another?
"Go for the eyes, Boo, go for the eyes!"
Fruny
Fruny
C) strtok() - warning, 1) it is not reentrant, 2) it destroys the original string.

C++) stringstreams.


“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan (C programming language co-inventor)

[edited by - Fruny on February 29, 2004 10:05:16 PM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Drakon
Drakon
I''m using c++... so, what are stringstreams and how do I use them?

or, point me somewhere that tells how.
"Go for the eyes, Boo, go for the eyes!"
Fruny
Fruny
stringstreams are standard stream classes, like fstream, but which read from/write to a C++ string instead of a file.

You can see some documentation here, have a look at this recent thread, search the forums (or google) for 'stringstream', or refer to your C++ manual.

Edit - also note that, in answer to your first question, you can compare C++ string objects simply with ==, !=, < and >, and read a line with getline (need fixing in VC6):


#include <iostream>
#include <string>

int main()
{
std::string str;
std::getline(std::cin, str);

if(str == "foo") std::cout << "you typed 'foo'." << std::endl;
}


This has the added benefit that you don't have to specify a string size beforehand.


“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan (C programming language co-inventor)

[edited by - Fruny on February 29, 2004 10:29:45 PM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.