could anybody explain, what are the different between declaration of the std::string mystring and char *mystring[];
And my code below, I want, this program read string in myfile (doc1.txt) then save it all to -> string str or str2 then (cout << str) one time, it will show the all string in the file but i could not solve it.
std::string mystring is a string object. Look at the reference documentation on this site to find out more information about that class.
char *mystring[] is a C-style array of pointers to char - in other words, each element of the array contains a pointer to a char.
getline(myfile, str2);// this code invalid argument
Well, yes, obviously it's invalid. getline takes a std::string as its second argument. str2 isn't a string, it's a vector of strings.
In any case, it will only ever read the line from the stream into the first element of the vector. Is that what the OP wants to do? If they're only ever going to use the first element of the vector, why use a vector at all?
I assume from the description posted by the OP, what they want is to store in memory the entire contents of the file being read, so presumably they want each line of the file to be stored in a separate element of the vector. Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
string str;
vector <string> allStrings;
ifstream myfile ("doc1.txt");
if(!myfile)
{
// NB Always better to put braces around a block, even when it has only 1 line
cout << "Error!\n";
}
else
{
while(!myfile.eof())
{
getline(myfile, str);
allStrings.push_back(str);
}
// Then iterate over the vector, outputting each element to stdout.
}