-
Problem with char
I'm having problem with my program here. See, I have an array of char* as data member in Action class. With the help of getFirst() function, I'm returning the value of the first element in the array. But, when I tried to print out this value in the test.cpp, it showed me some weird characters. It doesn't work. Please look at my codes:
--> Action.h
Code:
#ifndef ACTION_H
#define ACTION_H
class Action
{
public:
inline Action() {}
inline ~Action() {}
inline char **getCommand() { return command; }
inline char *getFirst() { return command[0]; }
inline char *getSecond() { return command[1]; }
void askCommand();
private:
char *command[5];
};
#endif
--> Action.cpp
Code:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#include "Action.h"
static const int NUM_OF_ARG = 5;
void Action::askCommand()
{
int i = 0;
char *res = NULL;
char temp[200];
cout << "> ";
cin.getline(temp, sizeof(temp), '\n');
res = strtok(temp, " ");
while( res != NULL && i < NUM_OF_ARG )
{
command[i] = res;
res = strtok(NULL, " ");
i++;
}
}
--> test.cpp
Code:
#include <iostream>
using namespace std;
#include "Action.h"
int main()
{
Action a;
a.askCommand();
char **string = a.getCommand();
cout << string[0] << endl; // this doesn't show me the value
cout << string[1] << endl; // this doesn't show me the value too
cout << a.getFirst() << endl; // this shows me some weird characters
cout << a.getSecond(); // this shows me weird characters too
return 0;
}
Could anybody please tell me what is wrong with the codes? Thanks in advance.
-
You've got an array of pointers that you point to local data that goes away.
If you want to capture the text, you'll need to allocate memory and copy it.
-
Could you show me how to allocate memory and copy it? I've tried to allocate memory using:
Code:
char *res = new char;
and copying it into the array using strcpy:
Code:
strcpy(command[i], res);
But, this strcpy statement has made the program encounters a runtime error.
-
In lazy mode, I just did this.
Code:
while ( res != NULL && i < NUM_OF_ARG )
{
command[i] = new char[strlen(res)+1];
strcpy(command[i], res);
res = strtok(NULL, " ");
i++;
}
-
Pff. That's pretty lazy, Dave. I mean where are all the colours?
You should consider using std::strings!
-
Well, thanks a lot. I find it working now. Huh, I'm feeling preety stupid now. It must've been very easy to figure out, lol.
Anyway, thanks. Yeah, using string is much better.