首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cin空间问题

cin空间问题
EN

Stack Overflow用户
提问于 2016-02-02 21:40:52
回答 1查看 410关注 0票数 0

所以我试着从cin和空格中读到一些东西,例如,如果我读到

代码语言:javascript
复制
AA 3 4 5
111 222 33

在cin中,我想将它们存储在一个字符串数组中。到目前为止我的代码是

代码语言:javascript
复制
string temp;
int x = 0;
string array[256];
while(!cin.eof())
{
    cin >> temp;
    array[x] = temp;
    x += 1;
}

但后来程序崩溃了。然后,我添加cout,尝试找出临时的内容,它显示:

代码语言:javascript
复制
AA345

那么,我如何将输入存储到一个包含空格的数组中呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-02 22:38:10

这里有一种可能,可以使用条目之间任意数量的空白来处理来自cin的输入,并使用boost库将数据存储在向量中:

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
int main() {
  std::string temp;
  std::vector<std::string> entries;
  while(std::getline(std::cin,temp)) {  
      boost::split(entries, temp, boost::is_any_of(" "), boost::token_compress_on);
      std::cout << "number of entries: " << entries.size() << std::endl;
      for (int i = 0; i < entries.size(); ++i) 
        std::cout << "entry number " << i <<" is "<< entries[i] << std::endl;                  
    }  
  return 0;
}

编辑

同样的结果可以在不使用可怕的boost库的情况下获得,例如,可以采用以下方式:

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
  std::string temp;
  std::vector<std::string> entries;
  while(std::getline(std::cin,temp)) {    
      std::istringstream iss(temp);
      while(!iss.eof()){ 
        iss >> temp;
        entries.push_back(temp);    
      }
      std::cout << "number of entries: " << entries.size() << std::endl;
      for (int i = 0; i < entries.size(); ++i)  
        std::cout<< "entry number " << i <<" is "<< entries[i] << std::endl;
      entries.erase(entries.begin(),entries.end()); 
    }
  return 0;
}

示例

输入:

代码语言:javascript
复制
AA 12  6789     K7

输出:

代码语言:javascript
复制
number of entries: 4
entry number 0 is AA
entry number 1 is 12
entry number 2 is 6789
entry number 3 is K7

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35164296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档