1

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?

5
  • 1
    Where is the input coming from? User input or from a pre-defined string? Commented Nov 19, 2012 at 14:37
  • 4
    mattgemmell.com/2008/12/08/what-have-you-tried Commented Nov 19, 2012 at 14:37
  • User input for example : cin>>number; Commented Nov 19, 2012 at 14:37
  • I've tried the getline function but it doesn't work. Commented Nov 19, 2012 at 14:38
  • Saying "it doesn't work" isn't helpful. You have to show us exactly what you tried, tell us what you expected to happen, and what happened. Commented Nov 19, 2012 at 14:39

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

7 Comments

okay but this will infinite loop , how can I stop this and continue to the other instructions ?
@Johnnie cin >> word will return false when there's no more word to read. Try it :-)
I've tried if(word == null) break; else names[i] = word; but I get no match for operator == in word==0; what's wrong?
Fwiw, unless you have a specific reason to examine the intermediate word prior to insertion, this can be reduced further to simply int i=0; while (cin >> names[i]) ++i;
@XiaoJia I believe 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.
|
3

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.

Comments

0

The most compact solution:

vector<string> words; 
copy(istream_iterator<string>(cin), 
     istream_iterator<string>(), 
     back_inserter(words));

This is @dasblinkenlight's solution, written using temporary variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.