2014-06-13 41 views
-2

我正在尝试编写一个代码,该文件从.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); 
} 

作为一个方面说明,这是我第一次张贴在这个网站,所以如果有与格式的任何问题,请让我知道,我会很乐意来解决这些问题更多。

+1

你的文件格式如何?你能给个例子吗 ?你能给这个程序的完整输出吗? – quantdev

+0

'const int ARRAY_SIZE = 45;'所以你肯定有46个有效的条目,无论你正在阅读哪个文本文件?!? –

回答

1

声音像文件没有被打开。你可以用这个测试:

namesOfKids.is_open() 

如果这返回false,那么打开文件时出现问题。

0

林不知道你的文件是如何被格式化的,但下面的代码是每行1名:

如果你有名字之间的分隔符:

name1;name2;name3; 

则可以使用:

while (getline(namesOfKids, tempName, ';')) 

以其他方式使用下列内容:

string tempName; 
    ifstream namesOfKids; 
    namesOfKids.open("LineUp.txt"); 

    const int ARRAY_SIZE = 45; 
    string students[ARRAY_SIZE]; 
    int count = 0; 

    if(namesOfKids.is_open()){ 
    while (getline(namesOfKids, tempName)) 
    { 
     students[count] = tempName; 
     cout << students[count] << endl; 
     count++; 
    } 
    }