How do I write with a string variable?
int length = write(fd, stringVariable.c_str(), stringVariable.length());
How do I read with a string variable?
char buf[MAX]; int length = read(fd, buf, MAX); string stringVariable = buf;
How do I declare a string variable?
Strings are arrays of characters, that end in a null byte. Declare
them like this ...
char buf[100];
How do I declare a string variable that will always hold a constant string?
If you have a string that will ALWAYS hold the same things, you
can do this
char *myHostName= "euclid.nmu.edu";
How do I copy a string from place to place?
Supose that lname has a value, and you wish target also had that value.
Do this
strcpy(target, lname);
This has the effect that target=lname would have if they were integer
variables
How do I append one string to another?
Try this
strcat(name, lname);
If name was "Scott" and lname was "Appleton", when this is done you
will have
in name "ScottAppleton". lname will be unchanged.
How do I find the length of a string?
int length = strlen(name);
How do I print out a string?
cout << name;
How do I compare strings?
if (strcmp(a, b) < 0)
cout << "A comes before B in alphebetical
order\n";
if (strcmp(a, b) == 0)
cout << "A is the exact same as B\n";
if (strcmp(a, b) > 0)
cout << "A comes after B in alphabetic
order.\n";
How do I convert a string to an integer or to a floating point number?
sscanf(buf, "%d", &int_variable);
sscanf(buf, "%f", &float_variable);
If you forget the "&" then the program will core dump.
Buf is the string to get the number from
How do I write a string to a socket?
int ret = write(file_descriptor, buf, strlen(buf)+1);
if (ret == -1) {
perror ("Arg. I had a writing booboo");
exit(1);
}
The "+1" is optional. If you do that, then you will also send the null byte. Sometimes you want to send the null byte. Some applications will barf if you send the null byte.
How do I read a string from a socket?
int len = read(file_descriptor, buf, BUFSIZE);
if (len == -1) {
perror("Arg! I'm illiterate (I cannot
read)");
exit(1);
}
buf[len] = 0;
That last line is optional. If the sender sent you a null byte, then you don't need it. However, it never hurts.
How do I find a particular character in a string?
Suppose you want to find the first "t" in a string. Use this
int position_of_first_t = index(University_Name, "t");
if (position_of_first_t == -1) {
cout << "There is no T you fool.
Mr T is upset!\n";
exit(1);
}
If you want to find the last character, and not the first, then use "rindex" and not "index".
What's the include file I need?
I suggest
#include <string.h>