0

プログラムの目標は、一連の括弧内にある場合にのみ、文字列 (char) 内の整数を抽出できるようにすることです。文字列がこれらの要件を満たしていない場合は、エラー メッセージを出力することも想定しています。

例:char str = "( 1 2 3)"; これは、整数 1、2、および 3 を検出したことを出力します。ただし、char str = " 1 2 3( 4 5 6);書式設定が不適切なため、str がエラー関数の呼び出しを返すとしましょう。文字列に数字や空白以外のものが含まれている場合は、エラーも出力する必要があります。最後に、終わりの括弧が見つかるまで、括弧の中を調べることを想定しています。

現時点では、任意の文字列を検索して整数を抽出できますが、数字以外に何かがあるかどうかを判断し、括弧内のみをチェックする方法がわかりません。

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 に答える