加载丑陋的输入 [英] Loading ugly input
本文介绍了加载丑陋的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要知道如何在c ++中加载这样的输入
I need to know how to load input like this in c++
{ [1, 1], [2, 10] , [-10, 20] }
在C中我可以这样写:
if ( ( scanf(" %c",&bracket) ) != 1 || bracket != '{') {
printf("Wrong input.\n");
return 1;
} // 1st bracket
while(1) {
if ( ( scanf(" %c%d%c%d%c",&bracket1,&arr[index][0],&dot,&arr[index][1],&bracket2) ) != 5 || bracket1 != '[' || bracket2 != ']' || dot != ',') {
printf("Wrong input.\n");
return 1;
}
if ( ( scanf(" %c",&tester) ) != 1 || ( tester != ',' && tester != '}' ) ) {
printf("Wrong input.\n");
return 1;
}
index++;
if ( tester == '}' )
break;
}
但我不知道如何加载它在c ++和修复所有错误的输入。我试图加载它,但它没有工作,不能修复错误的输入与cin。
But i have no idea how to load it in c++ and fix all the wrong inputs. I tried to load it with cin but it did not work and could not fix wrong inputs with cin.
推荐答案
令牌(或词典)中的输入。您输入的是7种类型的令牌: [] {},number end_of_file
。
You have to break the input in tokens (or lexemes). Your input is made of 7 types of tokens: [ ] { } , number end_of_file
.
// tokens definition
enum token
{
open_obj,
close_obj,
open_pair,
close_pair,
comma,
number,
end
};
// scanner
class scanner_type
{
std::istream& mis;
public:
token mt;
int mn;
scanner_type( std::istream& ais ) : mis( ais ) {}
token get()
{
std::ws( mis ); // eat white
char c;
if ( ! mis.get( c ) )
return mt = token::end;
switch ( c )
{
case '[': return mt = token::open_pair;
case ']': return mt = token::close_pair;
case '{': return mt = token::open_obj;
case '}': return mt = token::close_obj;
case ',': return mt = token::comma;
default:
if ( std::isdigit( c ) || c == '-' || c == '+' )
{
mis.unget();
mis >> mn;
return mt = token::number;
}
else
{
throw "unexpected character";
}
};
}
};
int main()
{
std::stringstream ss( "{ [1, 1], [2, 10] , [-10, 20] }" );
scanner_type sc( ss );
assert( sc.get() == token::open_obj );
assert( sc.get() == token::open_pair );
assert( sc.get() == token::number );
assert( sc.mn == 1 );
// ...
return 0;
}
阅读此处关于扫描仪。
这篇关于加载丑陋的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文