空间问题
cin issue with space
所以我试图从 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
希望这有帮助。
相关文章:
- 如何在不使用额外空间的情况下解决这个问题?
- 有关命名空间和模板参数的名称的问题
- 命名空间范围问题
- 在 c++ 中定义命名空间中模板类的友元函数时出现问题
- 从命名空间嵌入资源的问题(C++和CMake)
- 与自定义命名空间一起使用时实现 std::error_category、名称解析问题
- OPENCV在C /名称空间问题上
- 涉及STD :: __ CXX11名称空间的链接器错误 - 双ABI问题
- 关于"使用命名空间标准"的问题?
- 更改命名空间以自定义 Boost XML 的标记名称后的反序列化问题
- 删除标点符号和空间的问题
- 在将平截头体从摄影机空间转换为灯光空间以进行阴影映射方面存在主要问题
- 有关通过派生类在命名空间内继承的问题
- C++相同的命名空间问题
- 是详细命名空间中的使用指导性的问题
- 命名空间内类的循环依赖问题
- 命名空间外部变量的未定义参考/多重定义,C 结构问题
- C++11 中的命名空间问题?
- 关于取消引用和地址空间的基本C++指针问题
- C++中的编译错误可能是命名空间问题