串水果[200];
如何将字符串输入到数组中?
Example:
My mom has apples;
So , fruits array will contain:
fruits[0] = "My";
fruits[1] = "mom";
..........etc.
我怎样才能做到这一点?
如果您从标准输入读取:
int i = 0;
for (string word; cin >> word; i++)
names[i] = word;
如果您正在阅读 a string
,请istringstream
改用。
如果您想充分利用标准 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>
修复了必须猜测将输入多少个单词的问题,以及因猜测错误而导致的后果。
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.