我正在尝试编写一个代码,该文件从.txt文件中获取45个名称,然后将它们全部放入数组中。程序应该按字母顺序排列列表并显示给用户。我对我的大部分代码都很有信心,但是当我运行这个程序时,它并没有正确地将这些名字写入数组中。运行时,它将显示名称应该是45个空格,但不是名称本身。从循环的文本文件中提取字符串数据
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void sortStudents(string students[], int);
int main()
{
ifstream namesOfKids;
namesOfKids.open("LineUp.txt");
const int ARRAY_SIZE = 45;
string students[ARRAY_SIZE];
int count = 0;
while (count < ARRAY_SIZE)
{
string tempName;
namesOfKids >> tempName;
students[count] = tempName;
cout << students[count] << endl;
count++;
}
sortStudents(students, 45);
cout << "Here is the list of students from the class in\n";
cout << "alphabetical order\n\n";
for (count = 0; count < ARRAY_SIZE; count++)
cout << students[count] << endl;
cout << "\nThank you for running the program!\n Press any key to exit" << endl;
cin.get();
namesOfKids.close();
return 0;
}
void sortStudents(string students[], int size)
{
bool swap;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (students[count] > students[count +1])
{
students[count].swap(students[count+1]);
swap = true;
}
}
}while (swap);
}
作为一个方面说明,这是我第一次张贴在这个网站,所以如果有与格式的任何问题,请让我知道,我会很乐意来解决这些问题更多。
你的文件格式如何?你能给个例子吗 ?你能给这个程序的完整输出吗? – quantdev
'const int ARRAY_SIZE = 45;'所以你肯定有46个有效的条目,无论你正在阅读哪个文本文件?!? –