我需要从控制台读取用“;”分隔的数字直到我找到太空角色。输入应如下所示:3;1-2;-1;1;1;3;2。每组数字之间可以有一个以上的空格,我需要将每组数字插入到一个向量中。我最初的想法是这样的:
char c;
std::vector<double> coordinates;
while(std::cin >> c){
if(c != ' ' & c != ';'){
double a = c - 48;
coordinates.push_back(a);
}
}
这样做的问题是,如果我有负数,就不能使用ASCII将字符转换为整数。如果有人能给我另一种方法来做这种类型的阅读,或者能给我一些建议,我会非常赞同的!
下面是您想要的代码
您可以从中得到您想要的想法
不要忘记阅读注释
我还在结束输入时添加了char'e'
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::string cnum="";
std::vector<std::vector<long long>> mainVec;
int pos=0;
while (true)
{
std::vector<long long> cvec;
while (true) {
//std::cin wont get spaces
char c=getchar();
//we reached the space so lets parse it and go to next num
if (c == ';') {
int num;
try
{
//will throw if can't parse so inside of try cache
num=std::atoll(cnum.c_str());
cvec.push_back(num);
}
catch (const std::exception&)
{
std::cout << "can't parse the number";
}
//make ready for next num
cnum.clear();
}
else if (c == ' ') {
int num;
try
{ //will throw if can't parse so inside of try cache
num=std::atoll(cnum.c_str());
cvec.push_back(num);
}
catch (const std::exception&) {
std::cout << "can't parse the number";
}
//go to next vector
mainVec.push_back(cvec);
cvec.clear();
//or use std::move
break;
}
//end this operation
else if (c == 'e') {
int num;
try
{ //will throw if can't parse so inside of try cache
num= std::atoll(cnum.c_str());
cvec.push_back(num);
}
catch (const std::exception&) {
std::cout << "can't parse the number";
}
//add last vector and break the loops
mainVec.push_back(cvec);
goto rest;
}
else
cnum += c;
}
}
rest:
std::cout << "the end";
}
您可以自己进行优化(在每个if情况下减少被强奸的代码)
你需要的是一种在输入中向前看的方式。如果你知道下一个字符是空格,分号,数字还是减号,那么你就可以做出正确的决定读什么。
这里有一个函数可以帮你完成这个任务
int peek_char(istream& input)
{
int ch = input.get();
if (ch >= 0)
input.put_back(ch);
return ch;
}
有了这个函数,你不用读就知道下一个字符是什么。如果没有下一个字符(因为文件结束),它将返回一个负数。
您可以使用istream::peak
:
void read_sets(std::istream& is) {
while (is)
{
int next_char = is.peek();
if (next_char == ';') // ignore semicolons
is.ignore(1);
else if (next_char == EOF) // end of stream
break;
else if (std::isspace((unsigned char)next_char)) // end set
std::cout << '\n';
int number;
if (is >> number)
std::cout << number << ' ';
}
}
输入:
10;20;-88 1;2;0 -100;-99;1
输出:
10 20 -88
1 2 0
-100 -99 1