c++ - 从文件中读取字符串并排序

标签 c++ string file sorting ifstream

我的作业需要帮助。我不允许使用循环、if 语句、cout、cin、基本运算符和基本字符串以外的任何函数。数组是不允许的。我需要按字母顺序对文件中的名称列表进行排序,并输出哪些名称位于该行的前面和后面。但是,当我尝试运行我的代码时,它会停在读取文件的部分。该文件位于正确的位置,因为我已经用 cout 对其进行了测试。我不知道我做错了什么。任何帮助,将不胜感激! 继承人的代码:

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

int main()
{

    //Intialize variables
    string studentName;
    string firstEntry;
    string secondEntry;
    string first;
    string last;
    ifstream inputFile;
    string filename;
    int students;

    //Ask for amount of students
    cout << "Please enter the number of students in the class.\n(The number must be a whole number between 1 and 25.)\n";
    cin >> students;

    //Input validation
    while (students < 1 || students > 25)
    {
        cout << "\nInvalid value. Please enter a value between 1 and 25.\n";
        cin >> students;
    }

    //Get file name from user
    cout << "Please enter the name of the file with the list of students\n";
    cin >> filename;

    //Open the file
    inputFile.open(filename);
    if (inputFile)
    {
        while (inputFile >> studentName)
        {
            cin >> studentName;
            studentName = firstEntry;
            cin >> studentName;
            studentName = secondEntry;
            do
            {
                if (firstEntry < secondEntry)
                {
                    firstEntry = first;
                    secondEntry = last;
                }
                else
                {
                    firstEntry = last;
                    secondEntry = first;
                }
            } while (students = 30);

            if (firstEntry < first)
                firstEntry = first;

            if (secondEntry < first)
                secondEntry = first;

            if (firstEntry > last)
                firstEntry = last;

            if (secondEntry > last)
                secondEntry = last;

        }
        cout << first << " is the first student in line.";
        cout << last << " is the last student in line.";
    }
    else
    {
        cout << "Error opening the file.\nPlease restart the program and try again.";
        return 1;
    }

    inputFile.close();
    return 0;
}

最佳答案

         cin >> studentName;

这就是您的程序停止的原因。它正在等待您在键盘上键入内容。 (cin是C++中的标准输入)

关于c++ - 从文件中读取字符串并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162383/

相关文章:

c++ - 用于人类可读小数单位的 Boost 库

c++ - 基于Qt示例的Qt从QThread下载文件不起作用

xslt - 替换 XSLT 中的特殊字符

java - 放置双值二维数组读取文本

c++ - 有人知道这个 C++ 内联汇编的作用吗?

c++ - 如何使我的工厂的标题不依赖于它创建的模板化对象?

Java:检查字符串中是否有1次或多次

mysql - 如何将 URL 的整数子字符串内连接到整数?

file - 在 SQL Server Management Studio 中导入数据库(SQL 文件)

c - 从 C 中的 .dat 文件读取变量时出现问题