i not really understand as just beginner. can u explain more? |
I'll digress and explain strings.
The C and C++ Languages don't have a built in string type, but strings are provided thru their standard libraries.
In C, a string is an array of chars. For example:
declares an array 6 chars long and assigned the characters: 'w', 'e', 'n', 'd', 'y', 0 to the content. Note that strings in C have a 0 or NULL to mark the end.
Here's another example:
This creates an array of 4 chars with "Rye", and declares a pointer to a char, and assign's the address of that string to place. So place point's to the string "Rye".
When you declare your struct as:
1 2 3 4
|
struct Node
{
char* word;
};
|
you're saying a Node has a pointer to a string. You have the reponsibility of ensuring that that pointer points to something. If you're a beginner that's hard. If you're an expert that's hard to do correctly all the time.
An alternative is:
1 2 3 4
|
struct Node
{
char word[24];
};
|
This says your Node has enough space for a string 23 chars long including the trailing NULL. If you have a short string like "hello", you'll be wasting the extra space, and you can't hold a string that exceeds your 23 character limit.
A better definition is:
1 2 3 4
|
struct Node
{
string word;
};
|
In this case, the use of string takes care of all the mucky detail, and you can assign a string of any length to it. string is a C++ standard library class.
when my program read a txt file ... how can i put the string into a char* word? |
If your Node's word is a string instead of a char*, you assign it.
I've put an example below. This just shows how you'd do the assignment. It doesn't help with your linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <fstream>
#include <string>
using namespace std;
struct Node
{
string word;
};
int main(int argc, char** argv)
{
Node node;
string getcontent;
ifstream openfile(argv[1]);
while (openfile)
{
openfile>>getcontent;
node.word = getcontent;
}
return 0;
}
|