I'm trying to write a program that accepts user input for a file name. From there it stores the numbers in the file into an array, sorts them, then displays them. However, i'm getting large numbers similar to accessing an out-of-bounds array, but I can tell from the debugger i'm not.
#include <iostream>
using namespace std;
class TestScores
{
public:
TestScores();
TestScores(int scores);
~TestScores();
void AddScore(int newScore);
void DisplayArray();
void SortScores();
bool ArraySorted();
int AvgScore();
private:
int *scoresArray; //Dynamically allocated array
int numScores; //number of scores input by user
int scoreCounter;
const static int default_NumArrays=10; //Default number of arrays
};
#include <iostream>
#include "TestScores.h"
TestScores::TestScores()
{
scoresArray=new int[default_NumArrays];
scoreCounter=0;
numScores=default_NumArrays;
}
TestScores::TestScores(int scores)
{
scoresArray=new int[scores];
numScores=scores;
scoreCounter=0;
for(int i=0; i<scores;i++)
scoresArray[i]=0;
}
TestScores::~TestScores()
{
delete[] scoresArray;
}
void TestScores::AddScore(int newScore)
{
if(scoreCounter<numScores){
scoresArray[scoreCounter]=newScore;
scoreCounter++;
}
else
cout<<"More scores input than number of scores designated"<<endl;
}
void TestScores::DisplayArray()
{
for(int i=0; i<numScores; i++)
cout<<scoresArray[i]<<endl;
cout<<endl<<"This is scoresArray"<<endl;
}
bool TestScores::ArraySorted()
{
for(int i=0; i<(scoreCounter-1);i++){
if(scoresArray[i]<=scoresArray[i+1])
continue;
else
return false;
}
return true;
}
void TestScores::SortScores()
{
int tempValue;
while(ArraySorted()!=true){
for(int i=0; i<(scoreCounter-1); i++){
if(scoresArray[i]<=scoresArray[i+1])
continue;
else{
tempValue=scoresArray[i+1];
scoresArray[i+1]=scoresArray[i];
scoresArray[i]=tempValue;
}
}
}
}
int TestScores::AvgScore()
{
int sumScores=0;
if(scoreCounter>0){
for(int i=0; i<scoreCounter; i++)
sumScores+=scoresArray[i];
return (sumScores/scoreCounter);
}
else{
cout<<"There are no scores stored."<<endl;
return 0;
}
}
#include "TestScores.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Function prototypes
bool FileTest(ifstream& inData);
void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores);
int main()
{
int newNumScores=0;
string inputFile; //Contains name of the user file being used
//Opening file stream
ifstream inData;
//User prompt for input file
cout<<"Please enter the file name containing the student scores you wish to "
<<"have stored, sorted, and displayed."<<endl;
cin>>inputFile;
//Opening file streams
inData.open(inputFile.c_str());
while(FileTest(inData)==false){
cout<<"I'm sorry, the file you entered was not a valid file. "
<<"Please enter another file name, or enter q to exit"<<endl;
cin>>inputFile;
if(inputFile=="q")
return 0;
//Opening file streams
inData.open(inputFile.c_str());
}
inData>>newNumScores;
TestScores satScores(newNumScores); //Instantiating TestScores variable
StoreScores(inData, newNumScores, satScores); //Storing scores into array
satScores.DisplayArray();
satScores.SortScores();
satScores.DisplayArray();
cout<<endl<<"This is the array after sorting"<<endl<<endl;
cout<<"This is the average score "<<satScores.AvgScore()<<endl;
//Program pauses for user input to continue
char exit_char;
cout<<"\nPress any key and <enter> to exit\n";
cin>>exit_char;
inData.close();
return 0;
}
bool FileTest(ifstream& inData)
{
if(!inData)
{
cout<<"Your file did not open.\n";
return false;
}
return true;
}
void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores)
{
int userScore;
while(inData>>userScore){
satScores.AddScore(userScore);
}
}
My test file is random.dat and contains the following:
15
67
76
78
56
45
234
Based on looking through the debugger, I can tell that scoreCounter is incrementing correctly and that newScore contains the next value, so why isn't it being stored in the array? Thanks for the help
Okay, the problem is pretty simple: You pass satScores by value to StoreScores. This will only fill the local copy, change the signature of StoreScores to the following to fix:
void StoreScores(ifstream& inData, int& newNumScores, TestScores& satScores)
(Btw you don't actually use the newNumScores variable.)
The output is then as expected:
15
67
76
78
56
45
234
0
0
0
0
0
0
0
0
0
0
For further improvement of your code, see GMan's comment and Ben's answer.
You have a user-defined destructor but no copy-constructor or assignment operator. No wonder assignment doesn't work right, you get a leak of one buffer and double-free of the other.
Follow the Rule of Three. Or better yet, use a container that's already been debugged, like std::vector.
Related
As the title says, whenever I try to call a getter function to return the value of a private variable in an object pointer that is in a vector, it crashes. This causes my 2 other functions useless.
I know command == display and command == summary are not working properly. I did some debugging and found out that whenever I try to cout<<P_obj[i]->getnumber() for example, I crash.
Here is my code:
#include <string>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
class stock {
private:
int sharenumber;
float shareprice;
string sharename;
public:
stock(int x, string y,float z)
:sharenumber(x),sharename(y),shareprice(z)
{
}
int returnnumber(){
return sharenumber;
}
string returnname(){
return sharename;
}
float returnprice(){
return shareprice;
}
};
bool ispositive(int x){
bool a = false;
if (x>0){a = true;}
return a;
}
void buy(vector <stock*> list,int size){
int amount;
float price;
string symbol;
cout<<"Please enter the number of shares, the share symbol and the price of the share to make your purchase.\n";
do{
cout<<"Enter the amount: ";
cin>>amount;
if (ispositive(amount)==false){
cout<<"Please enter a positive number for the amount!\n";
}
}while(ispositive(amount)==false);
cout<<"Enter the symbol: ";
cin>>symbol;
do{
cout<<"Enter the stock price: $ ";
cin>>price;
if (ispositive(price)==false){
cout<<"Please enter a positive number for the price!\n";
}
}while(ispositive(price)==false);
list.push_back(new stock(amount,symbol,price));
cout<<"Your purchase has been made. Thank you for your time.\n\n";
}
void summary(vector <stock*> list,int size){
float cost = 0;
int stocktotal = 0;
for (int i = 0; i < size;i++){
cost = cost + (list[i]->returnprice()*list[i]->returnnumber());
stocktotal = stocktotal + list[i]->returnnumber();
}
cout<<"\nUser has made "<<size<<" purchases in total. The total number of stocks bought is "<<stocktotal<<". The total cost is "<<cost<<"."<<endl<<endl;
}
int main(int argc, char *argv[])
{
vector <stock*> P_obj;
bool cont = true;
bool last_cont = true;
char * check;
bool signal = false;
string command;
char done;
if (argc>1){
check = strstr(argv[1],".txt");
if (check!= NULL){
fstream tester;
tester.open(argv[1]);
if (tester.is_open()){
signal=true;}
}else{cout<<"Error has occurred. Please enter correct data file name with .txt extension.";}
if (signal){
cout<<"\nWelcome to the Golden Sacks! Enter a command to start your stock trading career.\n\n";
ofstream user_data(argv[1]);
while(cont==true){
bool e_valid = false;
cout<<"Enter command here: ";
cin>>command;
if (command == "buy"){
buy(P_obj,P_obj.size());
}
if (command == "summary"){
summary(P_obj,P_obj.size());
}
if (command == "display"){
cout<<"\nList of all purchases:\n";
for (int y = 0; y < P_obj.size(); y++){
cout<<P_obj[y]->returnnumber()<<" "<<P_obj[y]->returnname()<<" "<<"$"<<fixed<<setprecision(2)<<P_obj[y]->returnprice()<<endl;
}
cout<<endl;
}
if (command=="help"){
cout<<"Command list:\n";
cout<<left<<setw(2)<<"- buy\n";
cout<<left<<setw(2)<<"- display\n";
cout<<left<<setw(2)<<"- summary\n";
cout<<left<<setw(2)<<"- find <stock-symbol>\n";
cout<<left<<setw(2)<<"- amount>= <purchase-amount>\n";
cout<<left<<setw(2)<<"- help\n";
cout<<left<<setw(2)<<"- exit\n\n\n";
}
if (command == "exit"){
while (last_cont == true){
cout<<"Are you sure you want to quit? (Yy/Nn):";
cin>>done;
if (done == 'Y'||done == 'y'||done =='N'||done =='n'){
last_cont=false;
if(done=='Y'||done=='y'){
cont = false;
cout<<"Thank you for using Golden Sacks. We hope to see you soon!\n";
}
}else {cout<<"Please enter only Y|N or y|n, try again.\n\n";}
}
}
} //end of loop
for (int i = 0; i < P_obj.size(); i++){
user_data<<P_obj[i]->returnnumber()<<" "<<P_obj[i]->returnname()<<" "<<"$"<<fixed<<setprecision(2)<<P_obj[i]->returnprice()<<endl;
}
}
}else {cout<<"Too few arguments, enter a data file name with .txt extension to continue";}
}
vector <stock*> P_obj;
is not properly allocated. //memory leak
stock is not a user defined type like int or double.
so if you are using it as a pointer, use RAII technique with it, deallocate it in it's destructure
eg:
class Stock{
int* x{nullptr};
public:
Stock(...);//allocated here
~Stock(..);//deallocate here
};
you can further more defined new and delete operators
I've been coding for a basic Snake Game in C++. I wanted to store the top 5 high-scores in a text file so I could display them in the end.
I'm only showing the relevant code here.
Code:-
#include<fstream>
ofstream outfile("HighScore.txt");
ifstream infile("HighScore.txt");
int main()
{
int a[5]={0},temp;
infile.clear();
infile.seekg(0,infile.beg);
if(infile.is_open())
{
for(int i=0;i<=4;i++) infile>>a[i];
infile.close();
}
else cout<<"Unable to open";
char temp1;
Setup();
do
{
Draw();
Input();
Logic();
if(gameOver==0)
{
cout<<"\x1b[2J\x1b[1;1H"<<flush;
cout<<"\t\t\t\tSNAKE GAME"<<endl;
cout<<"\n\n\n\t\tYour score is:"<<score;
cout<<"\n\n\n\n\t\tDo you want to restart the game?\n\t\t Press y to continue\n\t\t";
temp1=(char)getch();
for(int i=4;i>=0;i--)//Used to make sure that the scores remain in a descending order
{
if(score>a[i])
{
if(i==4) a[i]=score;
else
{
temp=a[i];
a[i]=score;
a[i+1]=temp;
}
}
}
if(outfile.is_open())//Used to write the high-scores in "HighScore.txt"
{
for(int i=0;i<5;i++) outfile<<a[i]<<endl;
}
else cout<<"Unable to open";
outfile.close();
}
}
It seems that the code for writing the file is working and the output is always the current score at the top along with 4 0's.
For example:- If I scored 5 this time then the output will be
5
0
0
0
0
So according to me I'm not able to read the current values of the file because of which the values in the array a is always 0.
[I'm new here so I'm sorry if my formatting or description here is not up to the mark]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
Here is the full code in case I am wrong of the source of the problem:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
Be consistent in what you do. Including <stdlib.h> and <ctime> looks strange. Either include <cstdlib> and <ctime>, or include <stdlib.h> and <time.h>.
using namespace std;
Don't do this. This using imports all names from the std namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write std::time instead of the unqualified time. This makes it perfectly clear that you are referring to the time from the standard library instead of one that you might have defined yourself.
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
The cards should not be represented as strings, but as a separate data type called Card, with properties like suit and rank and a to_string method.
public:
void set_name(string a){name=a;}
To make your program fast, pass a as const std::string & instead of a simple string. This will prevent some copying of data. You should give a better name to the parameter, e.g. void set_name(const std::string &name) { this.name = name; }.
string print_name(){return name;}
This method does not print anything, therefore it must not be called print_name.
void card_generator();
Methods usually are named with verbs, not with nouns. So generate_cards would be a better name. But what does generate mean here? (I'm not a native English speaker, but would draw_cards describe it accurately?)
string set_cards(int c){return cards[c];}
A method called set_* usually modifies something. This one doesn't. Why did you name it this way?
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
Give better names to the parameters. From reading only this declaration, I have no idea what i and max_i might mean.
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a class Table. This allows you to have multiple independent tables, which is nice for a big tournament.
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
Before reading the choice1 variable, you must initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
Same here. The user hasn't yet entered anything, so how can you check it?
cin>>i;
Add error handling for every input by enclosing it in an if clause: if (std::cin >> i) {.
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
Don't use arrays, use a std::vector instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single 6 in your program.
player[0].card_generator();
max_i = i;//max_i is nb of players
Why do you call this variable max_i, when the comment says that max_players would be a better name?
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
What does the V in tempV mean?
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be % 52.
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
Captain Giraffe has answered this question in the comments. If any newbies like me face a similar problem look up what a debugger is, as errors like these are called run-time errors. Check this page for a simple explanation: http://www.cplusplus.com/forum/articles/28767/ .
My code works for putting data into the array but when I print it out, it always crashes after first number. There must be something wrong with my bubbledown function, could you point out what is wrong with it? Thank you in advance.
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
void bubbleup(int pq[], int back);
void bubbledown(int pq[], int front, int back);
void swap(int &a, int &b);
int main(){
ifstream infile;
ofstream outfile;
string input, output;
int size,number;
int front=1, back=0;
int *pq=new int[size]; // dynamically allocate array
cout<<"What's the input file name?"<<endl;
getline(cin, input); // get the input name
infile.open(input.c_str());// open the input file
while(!(infile.eof())){
infile>>number; // infile to an integer type variable first instead of an array. this is why your program doesn't work!!!!!
back++;
pq[back]=number;
bubbleup(pq,back);
for(int i=1;i<=back;i++)
cout<<pq[i]<<" ";
cout<<endl;
}
cout<<"what's the output file name?"<<endl;
getline(cin, output);
outfile.open(output.c_str());
while(back!=0){
cout<< pq[front]<<endl;
outfile<< pq[front]<<endl;
pq[front]=pq[back];
back--;
bubbledown(pq,front,back);
}
}
//bubbleup function
void bubbleup(int pq[], int back)
{
int fatherindex=back/2;
while(!(pq[back]>=pq[fatherindex])||!(back==1)){
if(pq[back]<pq[fatherindex])
swap(pq[back],pq[fatherindex]);
back=fatherindex;
fatherindex=back/2;
}
}
//bubbledown function
void bubbledown(int pq[], int front, int back){
int fatherindex=front,kidindex;
while(2*fatherindex+1 <= back){
kidindex=2*fatherindex+1;
if((kidindex+1<back) && (pq[kidindex]<pq[kidindex+1])){
kidindex++;
}
if(pq[fatherindex] > pq[kidindex]){
swap(pq[fatherindex],pq[kidindex]);
fatherindex=kidindex;
}
else
return;
}
}
//swap function
void swap(int &a, int &b){
int t=a;
a=b;
b=t;
}
A few problems to look at
You don't initialize size before using it, so your pq memory could be any size at all.
You are using 1-based access to your arrays, so make sure you allocate one more than you need.
while(!back==0) will work, but it is doing boolean logic on an int, then comparing the result with an int. while(back!=0) is a lot easier to read and will produce fewer compiler warnings.
Edit: also your bubbleDown function has an infinite loop when neither if test is triggered.
I have a program that is meant to take data from 2 separate text files, place them in arrays, compare them to each other, and output certain results. However, when I read the data from the files and try to display the data, I get a lot of weird symbols before it finally displays all the data in the text files. Here is the code.
// Ch07-Exam Grader.cpp : Defines the entry point for the console application.
//
//Libraries
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
//Prototypes
void initialization(void);
void proccess(void);
void eoj(void);
void writeIt(void);
void readIt(void);
void calculate(void);
//Global Variables
ifstream student;
ifstream correct;
int main()
{
initialization();
return 0;
}
//This function opens the files and calls the function to send the data into the array
void initialization (void){
correct.open("CorrectAnswers.txt");
readIt();
student.open("StudentAnswers.txt");
readIt();
}
void proccess (char c[], char s[], int length){
int correctCount = 0;
int incorrectCount = 0;
for (int i = 0; i< length; i++){
if (s[i] == c[i]){
correctCount = correctCount + 1;
} else {
incorrectCount = incorrectCount + 1;
}
}
}
void eoj (void){
}
void writeIt (void){
}
//This function will take the data and place it into seperate arrays
void readIt (void){
char studentArray[20]; //Array to hold the student answers
char correctArray[20]; //Array to hold the correct answers
//Loops to place data to seperate arrays
for (int i = 0; !correct.eof(); i++){
correct >> correctArray[i];
}
for (int j = 0; !student.eof(); j++){
student >> studentArray[j];
}
for (int i = 0; i < 20; i++){
cout << studentArray[i] <<endl;
}
proccess(correctArray, studentArray, 20);
}
void calculate (void){
}
And this is the result:
Only the letters are a part of the text file.
Why do you call readIt() twice in initialization() function? It looks like readIt() expects that both files are open, but you open first file, call readIt(), open second file, call readIt() again. May be the reason of the problem in this defect?