【问题标题】:C++ File I/O and PointersC++ 文件 I/O 和指针
【发布时间】:2013-11-18 08:35:53
【问题描述】:

我尝试创建一个使用输入文件“cardList.txt”的程序,该文件包含:

Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly

我想按姓氏的字母顺序对其进行排序。

主要:

#include <iostream>
#include <fstream>
#include <string>
#include "insertsortFunct.h"
using namespace std;

int main(void){
    ifstream inData;
    ofstream outData;
    const int listSize = 5;
    char cardList[listSize][25];
    instruct();
    openFile(inData, outData);
    buildList(cardList, inData);
    inData.close();
    sortList(cardList, listSize);
    cout << endl << "Your list is sorted" << endl;
    writeFile(cardList, outData);
    outData.close();
    return 0;
}

我在一个单独的文件中定义了这些函数:

#include "insertsortFunct.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void instruct(void){
    cout << "The program insertSort.cpp reads the file, cardList.txt " <<
        "into an array and" << endl;
    cout << "sorts the array using the selection sort algorithm." << endl;
    cout << "The sorted array is written to a file named cardList.srt." <<
        endl;
}

void openFile(ifstream& inputFile, ofstream& outputFile){
    inputFile.open("cardsList.txt");
    if(!inputFile.is_open())
        exit(1);
    outputFile.open("cardsList.srt");
    if(!outputFile.is_open())
        exit(1); 
}

void buildList(char (*array)[25], ifstream& inputFile){
    for (int i = 0; i < 5; i++)
        inputFile >> array[i];
}

void sortList(char (*list)[25], int length){
    int firstOutOfOrder, location;
    char temp[25];
    for (firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++){
        location = firstOutOfOrder;
        while ( location > 0 && list[location - 1] > list[location]){
            temp[25] = list[location][25];
            list[location][25] = list[location - 1][25];
            list[location - 1][25] = temp[25];
            location--;
        }
    }
}

void writeFile(char (*array)[25], ofstream& outputFile){
    for (int i = 0; i < 5; i++)
        outputFile << array[i];
}

但是我的程序只打印instruct(); 语句,似乎没有其他任何事情发生。该程序应该使用排序列表创建一个文件 cardList.srt 并且编译后不会出现在我的目录中。

【问题讨论】:

  • 返回码是多少?我想也许 openFile 找不到cardsList.txt 文件就退出了。
  • 是的。您应该检查输入文件 (cardsList.txt) 是否被正确读取。我创建了一个项目并将您的代码添加到其中。编译成功,运行正常。使用您的输入数据,这里是 cardsList.srt 文件的内容(不包括双引号),“Schmidt,HelgaAlvarez,RubenZowkowski,”
  • @DucPhan 这也是我得到的。我输入了错误的文件名。多谢你们。现在我必须弄清楚如何不删除全名并对其进行实际排序。

标签: c++ file header


【解决方案1】:

inputFile.is_open() 或 outputFile.is_open() 返回 false,因此调用了 exit()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-05-24
    相关资源
    最近更新 更多