0

该程序的目标是能够提取字符串(char)中的整数,前提是它们位于一组括号内。如果字符串不满足这些要求,我还想打印出一条错误消息。

例如:char str = "( 1 2 3)"; 这将打印它找到整数 1、2 和 3。但是假设 str ischar 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++;
    }

}

我曾尝试在 while 之后放置另一个 if 语句,看看它是否以 '(' 开头,但它什么也没做。请谢谢!

4

2 回答 2

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 */
    }
}
于 2013-02-19T22:00:39.403 回答
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();

    }
于 2013-02-19T22:48:08.903 回答