[英]Reading strings from file and sorting
我的作業需要幫助。 除語句,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 ++中的標准輸入)
我的真誠建議是始終使用筆和紙,並先記錄下您的要求。 在此基礎上寫下算法並將該算法轉換為代碼。 不幸的是,您在代碼中所做的一切都是錯誤的。 只需仔細考慮一下您在代碼中的工作,特別是下面的代碼:
while (inputFile >> studentName)//Think what are you doing here?
{
cin >> studentName;//???? reading into the same variable
studentName = firstEntry;//???? what are your doing here no value in firstEntry
cin >> studentName;//??here
studentName = secondEntry;//?? here no value in secondEntry
do
{
if (firstEntry < secondEntry)// this is not correct string comparison
{
firstEntry = first;//?? no value in first
secondEntry = last;//?? no value in last
}
如果您非常仔細地考慮所有這些,您將理解您的所有錯誤。
希望這個能對您有所幫助..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.