AYBODY KNOWS WHY THIS PROGRAM IS ABNORMAL?

#include <iostream>  // std::cout
#include <fstream>
#include <iomanip>
#include <string>    // std::string
#include <vector>    // std::vector<>
#include <algorithm> //std::for each()
using namespace std; // import "std" namespace into global namespace


   struct exam
{
   string examid;
   vector <int> total;   
}; 
  int myfile;
   int main()
	{
		ifstream stream1 ("STA83EXMSOL.txt");
		if ( !stream1 )
		
		{
		cout << "While opening a file an error is encountered" << endl;
		}
			else
			{
			cout << "Fail Di buka....." << endl;
			}  
			
				vector <exam> exams;
				exam aExam;
				string tempExamID;
				bool readEntireFile = false;     // set to true when reach end of file

			    stream1 >> tempExamID;    //  read in student id of first student
				while ( !readEntireFile )
				{

				aExam.examid = tempExamID;  //  new student
				int tempTotal;
				aExam.total.clear ();
				stream1 >> tempTotal;    // read in first exam code for this student
				aExam.total.push_back (tempTotal);  // add this exam code to current student's vector of exam codes
				bool newExam = false;   // true when a new student id is encountered
				while ( !newExam && !readEntireFile )
			
					{
		
					if ( stream1 >> tempExamID )   // successfully read in student id
			
						{
						if ( tempExamID.compare (aExam.examid) == 0 )  // student id is same as before
					
							{
							stream1 >> tempTotal;   // read in exam code
							aExam.total.push_back (tempTotal); // add this exam code to this student;s vector of exam codes
							}
				
						else
						newExam = true;   // student id is different from before.  Therefore new student.
						}
				
					else
					readEntireFile = true;  // end of file reached.  Want to exit inner and outer while loops
					}  // if new student, do not repeat this while loop
		
					exams.push_back (aExam);   // no more exam codes for this student.  Add aStudent to students vector
				}
	
				stream1.close ();  // We have read the entire file, so time to close it.
				
{
	ofstream myfile;
	myfile.open ("401.txt");
	if (myfile.is_open())
	{ 
		int temp, flag;
		for ( int i = 0 ; i < exams.size (); i++ )
		{ 
			flag = 0;
		
			for ( int j = 0;j<exams.at(i).total.size(); j++ )
			{
			myfile<<"\n"<<i+1<<":";   // output student id
			myfile<<" "<< exams.at (i).total.at(j)<<"\t" ;   // output list of exam codes for this student
			
			myfile<<"\n";
		
	  if ( exams.at (i).total.at(j + 1) >exams.at (i).total.at(j) )
	   {
	     temp =exams.at (i).total.at(j+1);
	    exams.at (i).total.at(j + 1) = exams.at (i).total.at(j);
	    exams.at (i).total.at(j)  = temp;
	     flag = 1;
	   }myfile << endl << "Double data initially in descending order" << endl;
}

		}
	}
    }
}

Dani AI

Generated

Immediate cause: an out‑of‑bounds access in the output/sorting loop. The inner writer loops over every element with j and then reads total.at(j+1) — that is undefined when j is the last index and will crash or produce “weird” behaviour. The adjacent-swap logic is also incomplete (one compare/swap per element) and the printing is mixed into the swap loop, which makes the output/order unpredictable.

Fixes and practical improvements (concise):

  • Stop accessing j+1 unless j + 1 < totals.size(). Better: sort the vector first and then print it.
  • Separate concerns: read/parse input, build data structures, then sort each student’s scores, then write output.
  • Rename the global myfile integer (it shadows the ofstream) and check file open errors early and return if open fails.
  • Use size_t or auto and range-for loops to avoid signed/unsigned bugs; check every operator>> when reading.
  • Turn on compiler warnings and sanitizers to catch UB: g++ -Wall -Wextra -g -O1 -fsanitize=address -std=c++11.

Example pattern for sorting + writing (replace with your variable names):

for (size_t i = 0; i < exams.size(); ++i) {
    auto &totals = exams[i].total;
    std::sort(totals.begin(), totals.end(), std::greater<int>()); // descending
    out << (i + 1) << ":";
    for (auto v : totals) out << ' ' << v << '\t';
    out << '\n';
}

For reading, a simpler and safer approach is while (stream >> id >> score) to parse pairs and store/group them as needed. Use assertions or print sizes during debugging to confirm each vector length before indexing.

Notes tied to the thread: correctly asked for sample input; given your file has single pair per ID, grouping logic will simply produce single-element vectors unless multiple lines share the same ID. Also heed ’s point about duplicate threads; keep one detailed thread and post a small reproducible example if problems persist.

Recommended Answers

All 3 Replies

Member Avatar for Member #46692

Define abnormal and give an example of your input file.

the input file is this....

0001 25
0002 20
0003 46
0004 56
0005 12
0006 22
0007 20
0008 18

Stop creating so many threads about the same topic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.