空间问题

cin issue with space

本文关键字:问题 空间      更新时间:2023-10-16

所以我试图从 cin 中读取一些东西,空格切断了它们,例如,如果我得到

AA 3 4 5
111 222 33

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

string temp;
int x = 0;
string array[256];
while(!cin.eof())
{
    cin >> temp;
    array[x] = temp;
    x += 1;
}

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

AA345

那么如何将输入存储到一个带有空格的数组中呢?

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

#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;
}

编辑

无需使用令人敬畏的提升库即可获得相同的结果,例如,通过以下方式

#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;
}

输入:

AA 12  6789     K7

输出:

number of entries: 4
entry number 0 is AA
entry number 1 is 12
entry number 2 is 6789
entry number 3 is K7

希望这有帮助。