简单的字符串问题 [英] simple string problem

查看:108
本文介绍了简单的字符串问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在输入类似12 + 13 = a的字符串;
IT也可以这样:12+ a = 25;或相反,

现在我想要我的输出是12 + 13 = 25;

现在的问题是我正在使用getline(cin,str)输入它;现在我不知道可以用来得到答案的字符

您对此有何看法.

I am inputing a string like 12+13 = a ;
IT can be like this also : 12+ a = 25 ; or the other way around ,

now I want that what my output is 12 + 13 = 25;

Now the ques is that I am inputing it using getline(cin,str); now I don''t know the characters in that which I can use to get the answer

what is your opinion to solve this .

推荐答案

我想您可以使用strtok函数.
函数链接 http://www.cplusplus.com/reference/clibrary/cstring/strtok/ [ ^ ]
I guess you can use strtok function.
Link for the function http://www.cplusplus.com/reference/clibrary/cstring/strtok/[^]


按照解决方案1中的说明将字符串拆分为令牌.

将整数累加器初始化为0,并将符号标志初始化为正.

扫描列表以识别令牌(忽略最后一个):

-每个偶数标记都是数字或变量名,

-每个奇数标记都是+或=.

要从变量名中分辨出一个数字,请使用sscanf(%d",...)并检查其是否解码了一个值.如果是数字,则以其符号累加;否则为0.如果变量,请保存符号.

当遇到=标记时,请将符号标志更改为负.

在分析字符串时,通过逐字复制所有标记来构造另一个字符串,但变量名除外,您将其替换为%d". (或者,将变量名称替换为原始字符串中的%d.)

通过printf格式化结果字符串,将构造的字符串和累加器值与变量的符号一起传递,取反.

你在这.大约十几行代码.对于格式错误的输入字符串完全不安全.
Split the string into tokens as explained in Solution 1.

Initialize an integer accumulator as 0, and a sign flag as positive.

Scan the list to identify the tokens (ignore the last one):

- every even token is either a number or a variable name,

- every odd token is either a + or an = .

To tell a number from a variable name, use sscanf("%d", ...) and check that it decodes one value. If number, accumulate it with its sign; if variable, save the sign.

When you meet the = token, change the sign flag to negative.

As you go analysing the string, construct another string by copying all tokens verbatim, except for the variable name, which you replace by "%d". (Alternatively, replace the variable name by %d in the original string.)

Format the result string by means of printf, passing the contructed string and the accumulator value taken with the sign of the variable, negated.

There you are. About a dozen lines of code. Totally unsafe to misformed input strings.


对于一个来说,这不是一个简单字符串"问题,您需要一个
For one, this is not a ''simple string'' problem, you want a Lexical Analyzer. There are libraries that solve the problem of tokenizing a text and structuring it in a sensible way, given set of grammatical rules. See the various references provided on the site linked above.


这篇关于简单的字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆