1

我无法从输入字符串中分离数字和字符。我的程序的目的是在后缀中加、减、乘和除, 所以我无法预测输入形式,因为它可以是从 2 2 3 + *(答案是 10)2 2 + 3 *(答案是 12)的任何东西. 所以我不能使用 sscanf 来提取数字和运算符字符,而不需要输入字符串的特定格式。我应该在这里做什么?

4

4 回答 4

2

好吧,要处理后缀,您将要实现一个堆栈,因此您应该在获得每个数字时将其压入堆栈,每个运算符从堆栈中弹出两个并将结果压回。

于 2010-03-06T10:43:43.273 回答
2

一种方法是使用scanf("%s")which 将字符返回到下一个空格。或者您可以使用getc一次获取一个字符。

编辑:

我从评论中看到您正在使用gets读取整行,在这种情况下,您最好在循环中使用strtok将行分成标记,然后查看每个标记的第一个字符来决定什么与它有关。

char line[MAX_LINE];
// read in the line 

char * pTok = strtok(line, " \t");
while (pTok)
{
    char ch = pTok[0];
    if (isdigit(ch))
       //handle number

    if (ch == '+')
       //handle addition operator
   
    ...
    pTok = strtok(NULL, " \t");
}
于 2010-03-06T10:43:49.623 回答
0

我会推荐使用 Boost.Spirit Qi,这是一个非常好的解析器库。第一个例子是一个计算器......

http://www.boost.org/doc/libs/1_42_0/libs/spirit/doc/html/spirit/introduction.html

仅标准库的解决方案:

// Get a line of user input (simplifies I/O)
std::string line;
if (!std::getline(std::cin, line)) throw std::runtime_error("Unable to read line");
// Process the line as an input string stream
std::istringstream iss(line);
while (true) {
    unsigned int val;
    if (iss >> val) {
        // TODO: Handle a numeric value (in val)
        continue;
    }
    iss.clear(); // Clear the error state
    char ch;
    if (!iss.get(ch)) break; // Break the loop if there is no more input
    // TODO: Handle a character (in ch)
}
于 2010-03-06T10:42:54.243 回答
0

我可能会通过抓取一整行来做到这一点,然后让一个函数接受一个字符串、一个偏移量和一个返回结构。返回结构包含令牌的开始和结束偏移量、令牌类型(运算符、参数)以及可能的其他一些内容。

或者,将其拆分为两个函数,一个检查数字,一个检查运算符。

于 2010-03-06T10:59:07.993 回答