所以我试着从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,尝试找出临时的内容,它显示:
AA345那么,我如何将输入存储到一个包含空格的数组中呢?
发布于 2016-02-02 22:38:10
这里有一种可能,可以使用条目之间任意数量的空白来处理来自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;
}编辑
同样的结果可以在不使用可怕的boost库的情况下获得,例如,可以采用以下方式:
#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希望这能有所帮助。
https://stackoverflow.com/questions/35164296
复制相似问题