Manipulation String

Hello Everybody

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.

string str;
vector <string> str2;
ifstream myfile ("doc1.txt");

if(!myfile)
cout << "Erro!\n";
else
{
while(!myfile.eof())
{
getline(myfile, str);
getline(myfile, str2);// this code invalid argument

}
std::cout << str << endl;
}
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.
Last edited on
This will work:

getline(myfile, str2.front())

Then again, you might as well use std::string
Last edited on
This will work:

getline(myfile, str2.front())

In the code posted by the OP, it won't, because the vector is empty, and the behaviour of front is undefined on an empty vector. See:

http://www.cplusplus.com/reference/vector/vector/front/

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.
} 
Thank you Mr. Mikey Boy,
i have understood your explanation
You're welcome :)
Topic archived. No new replies allowed.