1

そのため、これについてかなりの調査を行いましたが、出力を正しく機能させることができません。ファイルからデータを読み込み、リンク リストに格納する必要があります。使用されている while ループは、$$$$$ センチネルに到達したら停止する必要があります。次に、データを表示します (ID 番号 [ユーザー入力] で検索して) まだそこまでではありませんが、データを適切に表示して、今すぐ読み込んでもらいたいだけです。

私の問題は、データが $$$$$ で停止していないことを表示するときです (たとえ "inFile.peek() != EOF を実行して $$$$$ を省略しても)、まだ余分なゴミが発生しています。記録。

while ループと新しいノードの作成方法に関係があることはわかっていますが、他の方法で機能させることはできません。

どんな助けでも大歓迎です。

学生.txt

Nick J Cooley
324123
60
70
80
90
Jay M Hill
412254
70
80
90
100
$$$$$

assign6.h ファイル

#pragma once
#include <iostream>
#include <string>
using namespace std;
class assign6
{
public:
    assign6(); // constructor
    void displayStudents();


private:
struct Node
{ string firstName; 
  string midIni;    
  string lastName;
  int idNum;
  int sco1; //Test score 1
  int sco2; //Test score 2
  int sco3; //Test score 3
  int sco4; //Test score 4
   Node *next;
};
Node *head;
Node *headPtr;


};

assign6Imp.cpp // 実装ファイル

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

assign6::assign6() //constructor
{

ifstream inFile;
inFile.open("students.txt");

head = NULL;
head = new Node;
headPtr = head;
while (inFile.peek() != EOF) //reading in from file and storing in linked list
{

    inFile >> head->firstName >> head->midIni >> head->lastName;
    inFile >> head->idNum;
    inFile >> head->sco1;
    inFile >> head->sco2;
    inFile >> head->sco3;
    inFile >> head->sco4;

    if (inFile != "$$$$$")
    {
    head->next = NULL;
    head->next = new Node;
    head = head->next;
    }
}

head->next = NULL;

inFile.close();
}

void assign6::displayStudents()
{
int average = 0;
for (Node *cur = headPtr; cur != NULL; cur = cur->next)
{
    cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl;
    cout << cur->idNum << endl;
    average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4;
    cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl;
}
}
4

2 に答える 2

1

おそらく、そのように、代わりに行ごとに読むようにしてください。

const string END_OF_FILE_DELIM = "$$$$$";
ifstream inFile("students.txt");
string line;
while( getline(inFile,line) ){
   cout << "line = " << line << endl;
   if(line == END_OF_FILE_DELIM){
      break;
   }
   else{
       //create new Node with value = line;
   }
}
于 2012-10-30T23:26:03.420 に答える
0

これは機能しません:

if (inFile != "$$$$$")

ストリームを「$$$$$」と比較することはできません。ストリームから文字列を読み取り、それを「$$$$$」と比較することしかできません。

于 2012-10-30T23:20:18.343 に答える