如何让我的程序只检查括号内?

时间:2013-02-19 21:56:30

标签: c

该程序的目标是能够在字符串(char)中提取整数,只有它们在一组括号内。如果字符串不符合这些要求,我也打算输出错误信息。

例如:char str = "( 1 2 3)"; 这将打印它找到整数1,2和3.但是让我们说str char str = " 1 2 3( 4 5 6);将返回对我的错误函数的调用,因为它具有错误的格式。如果字符串包含任何不是数字或空格的其他内容,它也应该打印错误。最后,假设检查括号内部直到找到结束括号。

目前,我可以搜索任何字符串并提取整数,但我无法弄清楚如何确定除了数字之外是否还有其他内容并且仅在括号内检查。

void scanlist(char *str)
{
    char *p = str;
    while (*p) {
    if ((*p == '-' && isdigit(p[1])) || (isdigit(*p))) {
        int val = strtol(p, &p, 10);
        on_int(val);
    }
    else {
        p++;
    }

}

我已经尝试过另一个if语句,然后看看它是否以'('但是它没有做任何事情开始。请,谢谢!

2 个答案:

答案 0 :(得分:3)

你需要对你的职位持有一些状态。例如:

int inside_paren = 0;
while (*p) {
    switch (*p) {
    case '(':
        if (inside_paren)
            /* error */
        inside_paren = 1;
        break;
    case ')':
        /* ... */
        inside_paren = 0;
        break;
    default:
        if (!isdigit(*p) || !inside_paren)
            /* error */
    }
}

答案 1 :(得分:0)

希望这有帮助

int main()
    {
        //variable declerations
        int j = 0;
        // str is the string that is to be scanned for numbers
        string  str= "(123)";
        //iterator to point at individual characters in a string 
        //It starts at the beginning of a string
        //a string is an array of characters
        string::iterator p = str.begin();
        //if the iterator that i named p does not find the bracket at the begining 
        //prints out an error massage
        if(*p != '(')
        {
            cout<<"error";
        }
        //else if it finds a bracket at the begining goes into the loop
        // I use *p to veiw the content that the iterator points to 
        // if you only use p you will get the address which is a bunch of wierd numbers like A0Bd5 
        if(*p == '(')
        {
            //while loop to move the iterator p one caracter at a time until reach end of string
            while(p != str.end())
            {
                       // if end bracket is reached end loop
                       if(*p == ')')
                       {
                       break;
                       }
                //if it finds a digit prints out the digit as character not as int! 
                if(isdigit(*p))
                {

                    cout<<*p<<endl;
                }
                //increments the iterator by one until loop reach end of string it breaks
                p++;
            }
        }

        //to pause the screen and view results
        cin.get();

    }