1

串水果[200];

如何将字符串输入到数组中?

Example:
My mom has apples;
So , fruits array will contain:
fruits[0] = "My";
fruits[1] = "mom";
..........etc.

我怎样才能做到这一点?

4

3 回答 3

6

如果您从标准输入读取:

int i = 0;
for (string word; cin >> word; i++)
    names[i] = word;

如果您正在阅读 a string,请istringstream改用。

于 2012-11-19T14:37:45.370 回答
3

如果您想充分利用标准 C++ 库,请使用输入迭代器和 avector<string>而不是数组:

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);

使用vector<string>修复了必须猜测将输入多少个单词的问题,以及因猜测错误而导致的后果。

于 2012-11-19T14:42:36.230 回答
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.

于 2012-11-19T15:59:38.330 回答