...

View Full Version : CPP strings and user input



whackaxe
03-24-2004, 10:43 PM
hi peeps

i'm currently writing a small program that has a file system class (called C_fsystem)

this is it's code

[CODE]
class C_fsystem
{
protected:
char SZ_fpath [];
char SZ_fname [];
char SZ_fexten [];
public:
void setPath(char* TMP_buffer){strcpy(SZ_fpath, TMP_buffer);}
void setName(char* TMP_buffer){strcpy(SZ_fname, TMP_buffer);}
void setExten(char* TMP_buffer){strcpy(SZ_fexten, TMP_buffer);}
char fullName();
C_fsystem(char*, char*, char*);
};

C_fsystem::C_fsystem(char* PARAM_path, char* PARAM_name, char* PARAM_exten)
{
strcpy(SZ_fpath, PARAM_path);
strcpy(SZ_fpath, PARAM_name);
strcpy(SZ_fpath, PARAM_exten);
}

char C_fsystem::fullName()
{
char TMP_path [1000];
strcpy(TMP_path, SZ_fpath);
strcat(TMP_path, SZ_fname);
strcat(TMP_path, ".");
strcat(TMP_path, SZ_fexten);
}

int main()
{
C_fsystem myfile("D:\\my documents 2\\robin\\cpp sources\\terraserve\\", "main", "cpp");
cout<<myfile.fullName();
cin.get();
exit(0);
}
[CODE]

now everything compiles well, but i get a wierd symbol on my screen instead of the path, like i was expecting.

i'm getting the impression ive got compeltly the wrong end of the stick concerning strings.

another problem is, how do i initalise strings/char arrays so they can be any length? do i have to use dynamic memeory or not?

Unit
03-25-2004, 12:09 AM
it happens because your fullName function does not return anything!


// return type should be a string, not a char.
char C_fsystem::fullName()
{
char TMP_path [1000];
strcpy(TMP_path, SZ_fpath);
strcat(TMP_path, SZ_fname);
strcat(TMP_path, ".");
strcat(TMP_path, SZ_fexten);
// missing return value here - you cannot return TMP_path as its a local variable.
// consider rewriting this function in a different way.
}

whackaxe
03-25-2004, 06:12 PM
doh! i spent so much time fidling with stings i thought it would be that.

why can't i return TMP_path though? what is it lcoal to? the function or the class. in what does it differ to this for example(from cplusplus.com tutorial)

#include <iostream.h>

int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}

int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}

r is local to the function but it is still returned

thanks :)

Unit
03-26-2004, 12:17 AM
It is local to the function. When you return a string, only the reference to the string is returned. so in essence, you are returning a pointer to a local memory location which will not be available after the function call!

In your example, you are returning an int. and when you return an int, it returns the integer and not a reference to it. To apply the analogy, you can return a char in that way, but not a string.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum