有人可以帮我调试这个程序

时间:2014-04-13 22:55:31

标签: c++

到目前为止,这是我的代码,我认为它的工作正常,我相信问题出在我的数组上。

#include <iostream>
#include <cctype>
#include <fstream>

using namespace std;

const char FileName[] = "text.txt";

int main()
{
    string line;
    ifstream inMyStream(FileName);
    int c;
    int upperCaseCount[26] = { 0 };
    int lowerCaseCount[26] = { 0 };
    char oneLetter;

    if (inMyStream.is_open())
        {
            while (getline(inMyStream, line))
            {
                c += line.length();
            }

            for (unsigned n = 0; n < line.length(); ++n)
            {
                oneLetter = char(line[n]);
                if (oneLetter >= 'A' && oneLetter <= 'Z') 
                {
                    upperCaseCount[int(oneLetter) - 'A']++;
                }
                else if (oneLetter >= 'a' && oneLetter <= 'z')
                {
                    lowerCaseCount[int(oneLetter) - 'a']++;
                }
            }
        }
        inMyStream.close();

        cout << "Uppercase Characters: " << upperCaseCount << endl;
        cout << "Lowercase Characters: " << lowerCaseCount <<endl;
        cout << "Digits: " << c << endl;

    return 0;
}

这是我得到的输出---&gt;

  

C:\用户\屋\桌面\ Lab11&GT;测试

     

大写字符:0x28fcf4

     

小写字符:0x28fd5c

     

数字:1959532772

     

C:\用户\屋\桌面\ Lab11&GT;

2 个答案:

答案 0 :(得分:1)

我看到两个问题(我还有另一个问题需要你调试)。

您需要将变量c初始化到一些有用的起始值(可能为0)。

您需要遍历数组以打印其内容。您目前获得的奇怪输出是地址,而不是数组内容。

答案 1 :(得分:0)

这是一个用于计算upperCases lowerCases和数字的工作示例

#include <iostream>
#include <cctype>
#include <fstream>

using namespace std;

const char FileName[] = "text.txt";

int main()
{
    string line;
    ifstream inMyStream(FileName);
    int c=0;//counts digits
    int upperCount=0;//counts uppercases
    int lowerCount=0;//counts lowercases
    char oneLetter;

    if (inMyStream.is_open())
        {
            while (getline(inMyStream, line))
            {

                for (unsigned n = 0; n < line.length(); ++n)
                {
                    oneLetter = line[n];
                    if (oneLetter >= 'A' && oneLetter <= 'Z') 
                    {
                        upperCount++;
                    }
                    else if (oneLetter >= 'a' && oneLetter <= 'z')
                    {
                        lowerCount++;
                    }
                    else if (oneLetter >= '0' && oneLetter <= '9'){
                        c++;
                    }
                }
            }

        }

        inMyStream.close();

        cout << "Uppercase Characters: " << upperCount << endl;
        cout << "Lowercase Characters: " << lowerCount <<endl;
        cout << "Digits: " << c << endl;

    return 0;
}

希望它有所帮助;)