Hello.
I wrote a constructor with parameter char * for a class, whose objects are much like strings. And the program aborted, when it came to the part in the main function, where I used this constructor.
What I found unusual is that it aborted not in a typical VisualStudio2008-way, but like a usual windows application (e.g. a video-game).
Here's the code, showing class, constructor and main function:
class FString
{
private:
char *data;
char *end;
int size;
public:
FString(char * sample)
{
int i=0;
while (*(sample+i)!='\n') // I assume that sample ends with '\n' - that helps me find the end
{
i++;
}
size=i;
for (i=0; i<size; i++)
*(data+i)=*(sample+i);
end=(data+size-1);
}
}
void main()
{
char *test;
SCANSTR(test); //I use this function to input the string
FString obj(test); // and here the program crashes
}
So, does anyone have an idea- what's wrong with the constructor? :\
There are quite few things wrong with your code:
1. You don't allocate FString::data so this is the main reason why your program is crashing. Put data=newchar[size]; in constructor (EDIT: you already did this)
2. C-style strings always end with '\0' (null) character but you are checking for '\n'
1 2 3 4 5
int i=0;
while (*(sample+i)!='\n') // I assume that sample ends with '\n' - that helps me find the end
{
i++;
}
Are you trying to get length of the string? There is an easer way to get length of a string with strlen() function: int length_of_string=strlen(sample);
void SCANSTR(char *& test, int & len)
{
char a;
int check=1;
test=newchar[];
int i=0;
do
{
scanf("%c", test+i);
if (*(test+i)=='\n')
{
check=0;
}
i++;
}
while (check!=0);
len=i-1;
}
I was ashamed of my SCANSTR so I rewrote it to what you see in this post.
Now program runs fine, except when strlen(sample)==8.
One more thing, that changed after I used string-functions: I found some garbage in *data, when printing it.
(edit: for some reason, size, defined as size=strlen(sample);
equals 14. Which may be because I define sample as sample=newchar[]
and not as sample=newchar[certain_size] )
Thanks a lot. That works perfect, but I'd like to ask some questions.
1) Why is the argument of constructor "test.c_str()" and not just "test" ?
(edit: I`ve just read about c_str and as I understood, test.c_str ~ * test (if test would be char)
2) Is string variable the same, as char * ?
edit: The answer is probably 'no', so is there a way do something like this?
1 2 3
std::string test;
getline(cin,test);
char * st = &test;