空间问题 [英] cin issue with space
问题描述
所以我试图从cin读取一些内容,并用空格将它们切开,例如
So I was trying to read something from cin and spaces cut them, For example, if I got
AA 3 4 5
111 222 33
来自cin,我想将它们存储在字符串数组。
到目前为止,我的代码是
from cin, I want to store them in a string array. My code so far is
string temp;
int x = 0;
string array[256];
while(!cin.eof())
{
cin >> temp;
array[x] = temp;
x += 1;
}
,但是程序崩溃了。
然后我添加了cout来尝试弄清楚温度是什么,它显示:
but then the program crashed. Then I added cout to tried figure out what is in temp and it shows:
AA345
那么我如何将输入存储到带有空格的输入数组中呢?
So how can I store the input into an array with spaces cutting them?
推荐答案
这里有一种可能性,可以处理 cin
中的输入,并在条目之间使用任意数量的空格,并存储通过使用Boost库在矢量中获取数据:
Here's one possibility to treat an input from cin
with an arbitrary number of whitespaces between the entries, and to store the data in a vector by using the boost library:
#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;
}
编辑
无需使用令人敬畏的增强库即可获得相同的结果,例如,通过以下方式:
The same result could be obtained without using the awesome boost library, e.g., in the following way:
#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
希望这会有所帮助。
这篇关于空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!