在数组中搜索出现次数

时间:2015-05-15 15:34:17

标签: c++

此代码应显示包含6个选项的菜单。创建新文件,显示数字,总数和平均值,显示排序,搜索数字并告诉他有多少次出现,附加随机数,并显示最大值。

它运行并完成它应该做的大部分工作,但我无法获得searchNum函数来搜索输入的数字。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>

using namespace std;

//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);

int main()
{
    int choice = 0;
    string myFileName = "";

    do
    {
        cout << "** MENU **" << endl << endl;
        cout << "Current Data File: ";
        cout << fixed << setprecision(2) << showpoint;
        menu();

        cin >> choice;

        while (choice < 1 || choice > 7)
        {
            cout << "Menu Choice: ";
            cin >> choice;
            cout << endl;
        }
        switch (choice)
        {
            case 1:
            myFileName = createFile();
            break;
            case 2:
            displayNumTotalAverage(myFileName);
            break;
            case 3:
            displaySortedNums(myFileName);
            break;
            case 4:
            searchNum(myFileName);
            break;
            case 5:
            displayLargestNum(myFileName);
            break;
            case 6:
            appendRandomNum(myFileName);
            break;
        }

    } while (choice != 7);

    system("PAUSE");
    return 0;
}
void menu()
{
    cout << "\n\n(1)  Select / create data file(.txt file extension will be       added automatically)\n"
         << "(2)  Display all numbers, total, and average\n(3)  Display all numbers sorted\n(4)  "
         << "Search for a number and display how many times it occurs\n(5)  Display the largest number\n"
         << "(6)  Append a random number(s)\n(7)  Exit the program\n\nMenu Choice:";
}
string createFile()
{

    string myFileName;
    ifstream inFile;

    cout << "\nName of data file: ";
    cin >> myFileName;

    inFile.open(myFileName);
    if (inFile)
    {
        cout << myFileName;
    }
    else
    {
        cout << "\nFile not found, creating file.\n\n";
        ofstream outFile;
        outFile.open(myFileName + ".txt");
    }

    system("PAUSE");

    return myFileName;
}

void displayNumTotalAverage(string myFileName)
{
    ifstream inFile;

    const int SIZE = 50;
    int num[SIZE];
    int count = 0;
    int total = 0;
    double average = 0;

    inFile.open(myFileName + ".txt");
    while (!inFile)
        cout << "\nData File is empty" << endl << endl;

    while (count < SIZE && inFile >> num[count])
        count++;

    inFile.close();
    for (int index = 0; index < count; index++)
    {
        cout << num[index] << endl;
        total += num[index];
    }
    average = (float)total / count;
    cout << endl << "Total  :  " << total << endl << endl;
    cout << "Average: " << average << endl << endl;
    cout << "File Successfully Read" << endl << endl;


    system("PAUSE");
    return;
}


void displaySortedNums(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + ".txt");
    if(inFile.good())
    {
        const int SIZE = 50;
        int num[SIZE]; int counter = 0;
        while (counter < SIZE && inFile >> num[counter])
            counter++;
        inFile.close();
        for(int idx1 = 0; idx1 < counter; ++idx1)
            for(int idx2 = idx1; idx2 < counter; ++idx2)
                if(num[idx1] > num[idx2])
                {
                    int tmp = num[idx1];
                    num[idx1] = num[idx2];
                    num[idx2] = tmp;
                }
                for (int i = 0; i < counter; i++)
                {
                    cout << num[i] << endl;
                }
                cout << endl;
    }
    system("PAUSE");
    return;
}

void searchNum(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + "txt");
    const int SIZE = 50;
    int num[SIZE];
    bool found = false;
    int position = -1;
    int index = 0;
    int userNum = 0;
    int counter = 0;
    int numCount = 0;
    cout << "Search Number: ";
    cin >> userNum;
    cout << endl << endl;
    while (index < SIZE && !found)
    {
        if (num[index] == userNum)
        {
            found = true;
            position = index;
            numCount++;
        }

        index++;
    }

    cout << userNum << " occurs " << numCount << " times ";
    cout << "File Successfully Read\n\n";
    system("PAUSE");
    return;
}

void displayLargestNum(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + ".txt");
    const int SIZE = 50;
    int nums[SIZE];
    int count = 0;
    int highest;
    while (count < SIZE && inFile >> nums[count])
        count++;
    highest = nums[0];
    for (int i = 0; i < SIZE; i++)
    {
        if (nums[i] > highest)
            highest = nums[count];
    }
    cout << "\nLargest Number:  " << highest << endl << "File Successfully            Read" << endl << endl;
}

void appendRandomNum(string myFileName)
{
    cout << "i am in the appendRandomNum function - option 6" << endl;
    int num = 0;
    int count = 0;
    ofstream outFile;
    outFile.open(myFileName + ".txt", ios::app);
    cout << "How many random numbers: ";
    cin >> count;
    for (int i = 0; i < count; i++)
        outFile << rand() % 10 << endl;
    outFile.close();
    cout << endl << "Number(s) Added" << endl << endl;

    system("PAUSE");
    return;
}

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

我在searchNum函数中可以看到2个问题:

  1. 文件已打开,但num array未填充文件内容
  2. numCount将始终返回0或1.删除&#39;找到&#39;完全布尔变量,然后它将返回正确的numCount值。

答案 1 :(得分:1)

以下是一些他们似乎从未在编程课程中教授的重要规则:从小而简单的东西开始,一次增加一点复杂性,并单独开发新功能。

假设您有其他代码完美运行,并且您可以生成一个名为nums.txt的文件,如下所示:

7
9 
3
8
0
2
4
8
3
9

现在您要开发并测试searchNum函数。所以你写一个这样的main函数:

int main()
{
  string myFileName = "nums";
  searchNum(myFileName);
  system("PAUSE");
  return 0;
}

然后是searchNum函数:

void searchNum(string myFileName)
{
}

你编译并运行它,它什么都不做,到目前为止一直很好。

现在让它打开文件,读取第一个数字并显示它:

void searchNum(string myFileName)
{
  ifstream inFile;
  inFile.open(myFileName + "txt");

  int num;
  inFile >> num;
  cout << num << endl;
}

到目前为止一切顺利。现在遍历整个文件:

void searchNum(string myFileName)
{
  ifstream inFile;
  inFile.open(myFileName + "txt");

  int num;
  while(inFile >> num)
  {
    cout << num << endl;
  }
}

到目前为止一切顺利。现在计算8:

void searchNum(string myFileName)
{
  ifstream inFile;
  inFile.open(myFileName + "txt");

  int num;
  int count = 0;
  while(inFile >> num)
  {
    cout << num << endl;
    if(num == 8)
      ++count;
  }
}

你明白了。使用这种方法,您将获得干净的工作代码,并且您可以比尝试编写所有代码更快,然后修复所有错误。

答案 2 :(得分:1)

我在searchNum注意到的一些事情 inFile.open(myFileName + "txt");应为inFile.open(myFileName + ".txt");,后缀中缺少一个点。

阅读其余的答案并熟悉调试器,它将为您节省大量时间和挫折。

以下是您需要更正的代码示例。保持良好的工作并投入一些时间来使用调试器。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>

using namespace std;

//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);

int main()
{
    int choice = 0;
    string myFileName = "";

    do
    {
        cout << "** MENU **" << endl << endl;
        cout << "Current Data File: " << myFileName << (!myFileName.empty() ? ".txt" : "");
        cout << fixed << setprecision(2) << showpoint;

        menu();

        cin >> choice;

        while (choice < 1 || choice > 7)
        {
            cout << "Menu Choice: ";
            cin >> choice;
            cout << endl;
        }
        switch (choice)
        {
            case 1:
                myFileName = createFile();
                break;
            case 2:
                displayNumTotalAverage(myFileName);
                break;
            case 3:
                displaySortedNums(myFileName);
                break;
            case 4:
                searchNum(myFileName);
                break;
            case 5:
                displayLargestNum(myFileName);
                break;
            case 6:
                appendRandomNum(myFileName);
                break;
        }

    } while (choice != 7);

    cin.get();
    return 0;
}
void menu()
{
    cout << "\n\n(1)  Select / create data file(.txt file extension will be       added automatically)\n"
        << "(2)  Display all numbers, total, and average\n(3)  Display all numbers sorted\n(4)  "
        << "Search for a number and display how many times it occurs\n(5)  Display the largest number\n"
        << "(6)  Append a random number(s)\n(7)  Exit the program\n\nMenu Choice:";
}

string createFile()
{

    string myFileName;
    ifstream inFile;

    cout << "\nName of data file: ";
    cin >> myFileName;

    inFile.open(myFileName + ".txt", std::ifstream::in);

    if (inFile)
    {
        cout << myFileName;
    }
    else
    {
        cout << "\nFile not found, creating file.\n\n";
        ofstream outFile;
        outFile.open(myFileName + ".txt");
        outFile.close();
    }

    cin.get();

    return myFileName;
}

void displayNumTotalAverage(string myFileName)
{
    ifstream inFile;

    const int SIZE = 50;
    int num[SIZE];
    int count = 0;
    int total = 0;
    double average = 0;

    inFile.open(myFileName + ".txt");
    while (!inFile)
        cout << "\nData File is empty" << endl << endl;

    while (count < SIZE && inFile >> num[count])
        count++;

    inFile.close();
    for (int index = 0; index < count; index++)
    {
        cout << num[index] << endl;
        total += num[index];
    }
    average = (float)total / count;
    cout << endl << "Total  :  " << total << endl << endl;
    cout << "Average: " << average << endl << endl;
    cout << "File Successfully Read" << endl << endl;


    cin.get();
    return;
}


void displaySortedNums(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + ".txt");
    if(inFile.good()) 
    {
        const int SIZE = 50; 
        int num[SIZE]; int counter = 0; 
        while (counter < SIZE && inFile >> num[counter])         
            counter++;
        inFile.close();
        for(int idx1 = 0; idx1 < counter; ++idx1) 
            for(int idx2 = idx1; idx2 < counter; ++idx2) 
                if(num[idx1] > num[idx2])
                {
                    int tmp = num[idx1]; 
                    num[idx1] = num[idx2];  
                    num[idx2] = tmp; 
                }
        for (int i = 0; i < counter; i++)
        {
            cout << num[i] << endl;
        }
        cout << endl;
    }

    cin.get();
    return;
}

void searchNum(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + ".txt");
    const int SIZE = 50;
    int num[SIZE];
    int position = -1;
    int index = 0; 
    int userNum = 0; 
    int counter = 0;
    int numCount = 0;
    cout << "Search Number: ";
    cin >> userNum;
    cout << endl << endl;

    // Fill num array with inFile numbers.
    while (counter < SIZE && inFile >> num[counter++]);

    while (index < SIZE)
    {
        if (num[index] == userNum)
        {
            position = index;
            numCount++;
        }

        index++;
    }

    cout << userNum << " occurs " << numCount << " times ";
    cout << "File Successfully Read\n\n";
    cin.get();
    return;
}

void displayLargestNum(string myFileName)
{
    ifstream inFile;
    inFile.open(myFileName + ".txt");
    const int SIZE = 50;
    int nums[SIZE];
    int count = 0;
    int highest;
    while (count < SIZE && inFile >> nums[count])
        count++;
    highest = nums[0];
    for (int i = 0; i < SIZE; i++)
    {
        if (nums[i] > highest)
            highest = nums[count];
    }
    cout << "\nLargest Number:  " << highest << endl << "File Successfully            Read" << endl << endl;

}

void appendRandomNum(string myFileName)
{
    cout << "i am in the appendRandomNum function - option 6" << endl;
    int count = 0;
    ofstream outFile;
    outFile.open(myFileName + ".txt", ios::app);
    cout << "How many random numbers: ";
    cin >> count;
    for (int i = 0; i < count; i++)
        outFile << rand() % 10 << endl;
    outFile.close();
    cout << endl << "Number(s) Added" << endl << endl;

    cin.get();

    return;
}