代码顺序错误带来的警示

下面是11.22做的一道ACM题:

C.    Score

Time Limit: 1.0 Seconds    Memory Limit: 65536K



There is an objective test result such as "OOXXOXXOOO". An 'O' means a correct answer of a problem and an 'X' means a wrong answer. The score of each problem of this test is calculated by itself and its just previous consecutive 'O's only when the answer is correct. For example, the score of the 10th problem is 3 that is obtained by itself and its two previous consecutive 'O's.

Therefore, the score of "OOXXOXXOOO" is 10 which is calculated by "1+2+0+0+1+0+0+1+2+3".

You are to write a program calculating the scores of test results.

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing a string composed by 'O' and 'X' and the length of the string is more than 0 and less than 80. There is no spaces between 'O' and 'X'.

Output

Your program is to write to standard output. Print exactly one line for each test case. The line is to contain the score of the test case.

The following shows sample input and output for five test cases.

Sample Input

5
OOXXOXXOOO
OOXXOOXXOO
OXOXOXOXOXOXOX
OOOOOOOOOO
OOOOXOOOOXOOOOX

Output for the Sample Input

10
9
7
55
30


Source:  South Korea 2005 - Seoul

Problem ID in problemset: 2501



我的思路是运用string来解答,那么就要用到<string>文件头和s.length()函数。但是我的原始代码中求string长度的代码如下:


string answer;
int length = answer.length();
cin >> answer;


在这里我犯了一个错误:即代码顺序错误。在我的这段代码中,明显先定义了length为空string的长度(缺省值为0),所以无论怎样输入结果都为0;反之,如果我先输入string,再定义length并赋值,就不会出现这样的错误了。

所以,代码的前后顺序不能忽视!


另附AC代码如下:


#include <iostream>
#include <string>
using namespace std;


int main()
{
    string answer;
    int score = 0;
    int c = 0;
    int count;
    cin >> count;


    for (int i = 0; i < count; i++)
    {
        cin >> answer;
        int length = answer.length();


        for (int j = 0; j < length; j++)
        {
            if (answer[j] == 'O')
            {
                c++;
                score += c;
            }
            else
                c = 0;
        }
        cout << score << endl;
        c = 0;
        score = 0;
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/rr572078051/article/details/53282557