1

我想我正在接近一个更优雅的问题解决方案。我正在尝试创建一个程序,该程序输入数字文本文件,读取所有第一个数字,计算值 1-9 的出现总数,然后显示分析信息。我第一次尝试这样做时,我用 9 个不同的条件运行了一次 analyzeData 函数。从那以后,我开始尝试让 analyzedata(string filename) 通过 countLines(string filename, int number) 传递一个基本循环 [for (int i; 1 <= 9; i++)],然后显示新的计数。

但是,我已经到了我认为它已经完成但它不会运行的地步。我在第 59、81 和 88 行有三个错误。我回去检查括号和分号。我已经投入了大量的时间和精力来尝试制作高效的东西,而不是大量复制和粘贴厄运。

旁注-我在 Xcode 中工作,我能看到的唯一“输出”是“sh: PAUSE: command not found”,因为它不会运行。

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

// function to pass digit value to. analyzeData will
// call this function for each digit value 1-9

int countLines(std::string filename, int number) 
{
    int count=0;
    std::ifstream file;
    std::string first_digit;

    file.open( filename.c_str() );
    if ( !file.good() )
    {
        std::cout << "**ERROR: file not found!" << std::endl;
        exit(-1);
    }
    else
    {
        file >> first_digit;

        if (number == 0)// calling analyzeData with number=0 will compute total # lines / input values
        {
            while (!file.eof())
            {
                count++;
            }
        }
        else if (number != 0)
        {
            if (first_digit[0] == number)
            {
                count++;
            }
        }

    file.close();
    return count;
}

void analyzeData (std::string filename)
{
        std::ifstream file;
        std::string first_digit;

        file.open( filename.c_str() );
        if ( !file.good() )
        {
            std::cout << "**ERROR: file not found!" << std::endl;
            exit(-1);
        }
        else
        {
            std::cout << filename << std::endl;
            std::cout << countLines(filename,0) << std::endl; //total lines
            for (int i=1;i <= 9;i++) //sends i through countLines for each digit value
            {
                std::cout << i << ": " << countLines(filename, i) << std::endl;
            }
            std::cout << std::endl;
            file.close()
        }
}

int main(int argc, const char * argv[])
{
    analyzeData("***put file path here***");
    analyzeData("***put file path here***");
    analyzeData("***put file path here***");
    system("PAUSE");
    return EXIT_SUCCESS;
    return 0;
}

欢迎任何帮助或建设性的批评。

当我写这篇文章时,我有一个意识到的时刻!在第 45 行,我为字符串索引字符设置了一个条件,使其等效于一个 int 变量......这一定是某种错误的来源。谁能告诉我如何使 int 变量被读取为字符串?.c_str()??

4

0 回答 0