C++从键盘上读取字符串存入数组中

比如说~我输入“abc ddd f 1 2 3”,以空格分割每个单词,以回车结束
然后存入数组s[]中,s[1]=abc; s[2]=ddd; s[3]=1 ;s[4]=2; s[5]=3;
前提是,我也不知道要输入多少个单词,不知道数组大小。。。。
菜鸟真心不会啦。。只能上万能的百度来求解 T T。。求各位大神解答哇。。
主要想问 用哪个函数来【获取键盘输入的内容】是cin.get还是getline什么的??
能否把具体的循环代码写出来?~~~~

用stl的vector呗,可以动态扩展大小,用法与数据很相似。

大小不够的时候resize一下就行了。

 

结果在words变量中。

#include <iostream>
#include <string>
#include <vector>  

using namespace std;
 
int main()
{
 string inputStr;
 getline(cin, inputStr);
 vector<string> words;
 int pos = 0, lastPos = 0;

  while ((pos = inputStr.find(' ', lastPos)) != string::npos)
 {
  words.push_back(inputStr.substr(lastPos, pos - lastPos));
  lastPos = pos + 1;
 }

 if (lastPos < inputStr.size())
 {
  words.push_back(inputStr.substr(lastPos));
 } 

  system("pause");
  return 0;  
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-07-16
#include "stdio.h"
#include <string>
#include <vector>
using namespace std;

void main()
{
char s;
string t;
vector<string> str;
while(1)
{
s = getchar();
if(s=='\n')break;
if(s!=' ')
t+=s;
else 
{
str.push_back(t);
t="";
}
}
if(t.size())str.push_back(t);
for(int i=0; i<str.size();++i)
{
printf("%s\n",str[i].c_str());
}
}

本回答被提问者采纳
第2个回答  2014-10-25
用字符串分割吧,下边用的是#号, 你用空格就行了
char str[] = "now # is the time for all # good men to come to the # aid of their country";
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
相似回答