Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple String question. 1

Status
Not open for further replies.

Elena

Technical User
Oct 20, 2000
112
US
Hi,

As I am new to C/C++, I for some reason cannot get this simple concept.

If declare a string like:

char string[];

Shouldn't I be able to assign it a value later on? Like:

if(something is true)
string = "This is a string.";
else
string = "This is not a string.";


Can someone explain how to do this, please?

I have also tried it this way:

char *string[50];

then

if (something is true)
*string = "This is a string.";
else
*string = "This is not a string.";


which did work, but I also wanted to use strcat to combine two strings, but that doesn't work either. I guess there some fundamental simple thing that I don't get.

Thanks for the help,

Elena


 
> As I am new to C/C++
Well the first thing is to decide whether you're programming in C or C++.
C/C++ is some random mixture which will cause you problems somewhere along the line.

Since this is the C forum, this is a C answer.

Code:
char string[100];  /* 99 chars and a \0 */
if(something is true)
  strcpy(string,"This is a string.");
else
  strcpy(string,"This is not a string.");

If you want to strcat() to the end of string, then you can do that with
[tt]strcat(string,"hello world");[/tt]

Whilst your exercise with pointers works fine for fixed strings, it is not going to work when you start trying to use strcat() on them. Fixed strings are not modifyable.

--
 
I figured out what the fundamental thing was that I wasn't getting.

A string is a character array. So the variable name is actually pointer the beginning of the array, not the contents of the array itself. That's why I could not assign a string to the variable (because its a memory address). I have to use strcpy instead. After I fixed that, strcat worked also.

I was referring to two books on C and C++, neither of which pointed that out. Then, I looked in the Borland Turbo C++ manual, and found it. AHA!!

Thanks for the help,

Elena
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top