string fruits[200];
How can I input a string into the array ?
Example:
My mom has apples;
So , fruits array will contain:
fruits[0] = "My";
fruits[1] = "mom";
..........etc.
How can I do that?
string fruits[200];
How can I input a string into the array ?
Example:
My mom has apples;
So , fruits array will contain:
fruits[0] = "My";
fruits[1] = "mom";
..........etc.
How can I do that?
If you're reading from the standard input:
int i = 0;
for (string word; cin >> word; i++)
names[i] = word;
If you're reading from a string, use istringstream instead.
cin >> word will return false when there's no more word to read. Try it :-)word prior to insertion, this can be reduced further to simply int i=0; while (cin >> names[i]) ++i;while (cin >> names[i++]) may be incorrect, as I believe even in failure the post-increment is applied, in which case your resulting count will always be off by one. Someone check me on that.If you would like to use the standard C++ library to its fullest, use input iterators and a vector<string> instead of an array:
vector<string> words;
back_insert_iterator< vector<string> > back_iter (words);
istream_iterator<string> eos;
istream_iterator<string> iit (cin);
copy (iit, eos, back_iter);
Using vector<string> fixes the problem of having to guess how many words would be entered, and living with the consequences of making a wrong guess.