entries of array of an object not updating - c++

I have a class called Random with the following variables
private:
int Numbers[10];
int NrHighest;
int NrLowest;
int Index;
int IndexH;
int IndexL;
and a friend function called friend voidinsertNumbers(Random Random1)`
void insertNumbers(Random Random1)
{
string line;
int one,two,three;
int columOne[10];
int columTwo[10];
int columThree[10];
ifstream myfile("Numbers.dat");
if (myfile.is_open())
{
int i = 0;
while ( getline (myfile,line) )
{
sscanf(line.c_str(),"%i %i %i",&one,&two,&three);
columOne[i] = one;
columTwo[i] = two;
columThree[i] = three;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
switch(run)
{
case 0 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columOne[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 1 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columTwo[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 2 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columThree[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
}
run ++;
};
I have a cout << Random1.Numbers[i] << endl; to check if the numbers are saved to Random1.Numbersand the output is
Output
But the problem come when I try to display the objects here
cout << Random1;
cout << Random2;
cout << Random3;
calling the overloaded function which is also a friend function friend ostream &operator<<( ostream &output,const Random & Random1);
ostream &operator<<( ostream &output,const Random & Random1)
{
for(int i = 0;i<10;i++)
{
cout << Random1.Numbers[i] << " ";
}
cout << endl << Random1.NrHighest << endl << Random1.NrLowest << endl << Random1.Index << endl << Random1.IndexH << endl << Random1.IndexL << endl;
return output;
};
I get the Defauts values set here
Random()
{
Numbers = {0,0,0,0,0,0,0,0,0,0};
NrHighest = 0;
NrLowest = 0;
Index = 0;
IndexH = 0;
IndexL = 0;
};
Rather than the new vaules, heres the output of the overloaded operator<< function Output
I can seem to figure out why the objects doesn't get updated.If you neem more info please ask.
Thanks in advance.

In your function void insertNumbers(Random Random1) you are adding values to Random1 but you are passing it by value. Hence, when this function is called with a Random instance, it makes a copy of it, adds values to it and finally destroys it. You will solve this problem by passing Random1 by reference: void insertNumbers(Random &Random1)

Related

I want this c++ program to find the the words starting with user entereed letter and print them using a new function

I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}

Option to print output to screen or given file name (c++)

I would like option 2 to pass the output to a typed file name. However, the program is creating the file but not passing the output to the file. I think just using ostream is fine here, but don't know how to go about it.
void displayTable(int n, char op) {
int printOption;
string outputFileName;
ofstream createOutputFile;
while (true) { //option for print screen or print to file
cout << "Select: \n1) Print on Screen \n2) Print to a file name \nSelection: ";
cin >> printOption;
if (printOption == 1)
break;
else if (printOption == 2){
cout << "Type in the name for the output file." << endl;
cin >> outputFileName;
createOutputFile.open(outputFileName);
break;
}
else
cout << "Please enter a valid number." << endl;
}
int max = getMaxSize(n, op);
cout << setw(max) << op << "|";
for (int i = 1; i <= n; ++i) {
cout << setw(max) << i;
}
cout << endl;
for (int i = 0; i < max; ++i) {
cout << "-";
}
cout << "+";
for (int i = 0; i < n * max; ++i) {
cout << "-";
}
cout << endl;
for (int i = 1; i <= n; ++i) {
cout << setw(max) << i << "|";
for (int j = 1; j <= n; ++j) {
cout << setw(max) << getValue(i, j, op);
}
cout << endl;
}
cout << endl;
createOutputFile.close();
}
You are not printing anything to createOutputFile, everything is being printed to cout instead. That is why to don't see anything in the file, and everything in the console.
The easiest way to solve your issue is to redirect cout to createOutputFile's output buffer, eg:
auto cout_buff = cout.rdbuf();
...
createOutputFile.open(outputFileName);
cout.rdbuf(createOutputFile.rdbuf())
// all cout outputs will now go to the file...
...
cout.rdbuf(cout_buff); // restore when finished...
Otherwise, move your print logic to a separate function that takes an ostream& as a parameter:
void doMyLogic(ostream &os)
{
// print to os as needed...
}
...
if (printOption == 1) {
doMyLogic(cout);
break;
}
if (printOption == 2) {
...
ofstream createOutputFile(outputFileName);
doMyLogic(createOutputFile);
break;
}
...

Input value of a variable is also being saved into another variable

In the below code on method called get_array() problem occurs because the capacity variable change to after first input given by user in the console
and capacity value assign to what value given by user
I am not sure what's happening but it's kind of irritating me or did I missed some basic knowledge ? Please help
#Software
I am using CodeBlocks v17.12
#OS
Windows 10 Home
#include <iostream>
using namespace std;
class LinearSearch
{
int my_arr[];
int capacity, c, val;
public:
LinearSearch()
{
this->capacity = 0;
this->c = 0;
this->val = 0;
}
void get_array()
{
cout << "Define number of elements in the array: ";
cin >> this->capacity;
for( int i = 0; i < this->capacity; i++ )
{
cout << "Enter value " << i+1 << " - " << this->capacity << " : ";
cin >> this->my_arr[i];
}
for( int k = 0; k < capacity; k++ )
{
cout << my_arr[k] << endl;
}
cout << endl;
}
void search_value()
{
cout << endl << "Enter a value to search: ";
cin >> this->val;
for(int j = 0; j < capacity; j++)
{
if(my_arr[j]==val)
{
cout << endl << this->val << " value found in the array at index array[" << j << "] value number " << j+1 << "." << endl << endl;
c++;
break;
}
}
if(this->c==0)
cout<<endl<<this->val<<" value not found in the array."<<endl<<endl;
}
};
int main()
{
int choice;
LinearSearch obj;
while( true )
{
cout << "0) Exit\n1) Insert Data\n2) Search Data\n\nEnter Option: ";
cin >> choice;
switch( choice )
{
case 0:
return 0;
case 1:
obj.get_array();
break;
case 2:
obj.search_value();
break;
default:
cout << "\nWrong Option!!\n\n";
break;
}
}
return 0;
}
int my_arr[]; is not valid standard C++ and even in C it must appear only at the end of the member list as so-called flexible array member.
You should use std::vector<int> my_arr; instead. (Requires #include<vector>.)
You can then add new elements to it with my_arr.push_back(/*some number here*/); or you can resize the array with my_arr.resize(/*new size here*/);.

c++ - undeclared identifier (operator ostream) with inheritance [duplicate]

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 5 years ago.
I can not figure out why there is an error because everything looks fine to me, I've loaded all the code, but the error is in the print operator only function. When I run the program he takes me to this function.
I have an error, but I can not understand why.
Would appreciate help.
When I run the program the error is here(in CatsPen.h):
Error 1 error C2065: 'os' : undeclared identifier
c:\users\name\documents\visual studio 2013\projects\exe8\CatsPen.h 33 1
EXE8
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
main:
#include <iostream>
#include "CatsPen.h"
using namespace std;
int main(){
CatsPen pen1;
int choice = -1;
while (choice == -1){
cin >> choice;
cout << "Enter your choice: " << endl;
cout << "1-add street cat " << endl;
cout << "2-add siami cat " << endl;
cout << "3-print cats " << endl;
cout << "4-print how many cats " << endl;
cout << "5-exit" << endl;
if (choice == 1){
pen1.addStreet();
}
}
system("pause");
return 0;
}
CatsPen.h:
include "Cat.h"
#include <iostream>
using namespace std;
#ifndef CatsPen_H
#define CatsPen_H
class CatsPen{
private:
StreetCat * street;
SiamiCat * siami;
int countStreet;
int countSiami;
int numOfCats;
int emptyCage;
public:
CatsPen();
~CatsPen();
int getCountCat(){
return countStreet + countSiami;
}
bool Place();
bool addStreet();
bool addSiami();
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
};
#endif;
CatsPen.cpp:
catsPen.h"
CatsPen::CatsPen(){
this->street = NULL;
this->siami = NULL;
this->numOfCats = 0;
this->countStreet = 0;
this->countSiami = 0;
this->emptyCage = 5;
}
CatsPen::~CatsPen(){
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[] street;
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[]siami;
}
bool CatsPen::Place(){
if (emptyCage > 0){
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
bool CatsPen::addStreet(){
if (Place() == true){
if (countStreet == 0){
this->street = new StreetCat[1];
cin >> this->street[countStreet];
cout << this->street[countStreet];
}
else if (countStreet > 0){
StreetCat* copyArray = new StreetCat[this->countStreet + 1];
for (int i = 0; i < countStreet; i++){
copyArray[i] = street[i];
cin >> copyArray[countStreet];
delete[] street;
cout << copyArray[countStreet];
street = copyArray;
}
countStreet++;
emptyCage--;
}
cout << "no have place in the pen" << endl;
return false;
}
}
bool CatsPen::addSiami() {//add siami cat to the pen
if (Place() == true) {
if (countSiami == 0) {
this->siami = new SiamiCat[1];
cin >> this->siami[countSiami];
cout << siami[countSiami];
}
else if (countSiami > 0) {
SiamiCat*copyArray = new SiamiCat[this->countSiami + 1];
for (int i = 0; i < countSiami; i++)
copyArray[i] = siami[i];
cin >> copyArray[countSiami];
cout << copyArray[countSiami];
delete[]siami;
siami = copyArray;
}
countSiami++;
emptyCage--;
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
thank's...
There is a typo in this definition
friend ostream& operator<<(ostream&, const CatsPen& other){
^^^
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
The parameter name os is missed.
friend ostream& operator<<(ostream &os, const CatsPen& other){
^^^

When I read from a file in C++ it, displays the numbers more times then it should

I am coding a program that allows the user to name a file and open or create that file. Then they are able to read the info from that file in different ways or write more info into the file. The problem is that when I choose an option to read the file it first reads it fine then when I try to read it a different way it has two sets of numbers, as if it is reading the file twice.
I am unable to pin point the problem to any one function, and it is hard the explain the problem so I am posting the whole program. if you could help that would be great. Thank you in advance.
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(), f1(), f2(), f3(), f4(), f5(), f6(), f7();
string file;
const int NUM_DATA = 50;
double data[NUM_DATA], temp;
int num = 0;
int main()
{
int choice;
do
{
system ("cls");
cout << " ** MENU ** \n\n";
cout << "Current Data File: " << file << "\n\n";
cout << "(1) Select/Create data file (.txt file extension will be added automatically)\n";
cout << "(2) Display all the numbers, total and average\n";
cout << "(3) Display all the numbers from smallest to the largest\n";
cout << "(4) Select a number and display how many times it shows up\n";
cout << "(5) Display the largest number\n";
cout << "(6) Append random number(s)\n";
cout << "(7) Exit the program\n\n";
do
{
cout << "Choice: ";
cin >> choice;
cout << endl;
}
while (choice < 1 || choice > 7);
switch (choice)
{
case 1: f1();
break;
case 2: f2();
break;
case 3: f3();
break;
case 4: f4();
break;
case 5: f5();
break;
case 6: f6();
break;
}
}
while (choice != 7);
return 0;
}
// Select file
int f1()
{
cout << "Name of data file: ";
cin >> file;
file = file + ".txt";
ifstream fileI;
fileI.open(file.c_str());
if(!fileI)
{
cout << "\nFile not found, creating file. \n\n";
ofstream fileO;
fileO.open(file.c_str());
fileO.close();
}
else
{
cout << "\nFile successfully read. \n\n";
fileI.close();
}
system("pause");
return 0;
}
// Display all the numbers, the total and the average
int f2()
{
f7();
ifstream fileI;
fileI.open(file);
double total = 0;
double average;
for (int count = 0; count < num; count++)
{
total += data[count];
cout << data[count] << endl;
}
average = total / num;
cout << "Total: " << total << endl;
cout << "Avearage: " << average << "\n\n";
fileI.close();
system("pause");
cin.ignore();
return 0;
}
// Display all the numbers from smallest to largest
int f3()
{
f7();
ifstream fileI;
fileI.open(file);
for(int i = 0; i < num; i++)
{
for(int j = 0; j < num; j++)
{
if(data[i] < data[j])
{
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
for (int count = 0; count < num; count++)
{
cout << data[count] << "\n\n";
}
fileI.close();
system("pause");
return 0;
}
// Display how many times a number shows up
int f4()
{
f7();
ifstream fileI;
fileI.open(file);
int numb, times = 0;
cout << "Search number: ";
cin >> numb;
cout << endl;
for (int count = 0; count < num; count++)
{
if (numb == data[count])
{
times ++;
}
}
cout << numb << " ocurrs " << times << " times." << "\n\n";
fileI.close();
system("pause");
return 0;
}
// Display the largest number
int f5()
{
f7();
ifstream fileI;
fileI.open(file);
int large = data[0];
for (int count = 0; count < num; count++)
{
if (large < data[count])
{
large = data[count];
}
}
cout << "Larget number: " << large << "\n\n";
fileI.close();
system("pause");
return 0;
}
// Append one or more random numbers
int f6()
{
ofstream fileO;
fileO.open(file, ios::app);
int rndm, numbs;
srand(time(NULL));
cout << "Add how many numbers: ";
cin >> rndm;
cout << endl;
for (int count = num + 1; count <= num + rndm ; count++)
{
numbs = (rand()%50+1);
fileO << numbs << endl;
}
cout << "Data succesfully written.\n\n";
fileO.close();
system("pause");
return 0;
}
//Array function
int f7()
{
ifstream fileI;
fileI.open(file);
fileI >> temp;
while (num < NUM_DATA && !fileI.eof())
{
data[num] = temp;
++num;
fileI >> temp;
}
fileI.close();
return num;
}
It's because, in f7(), you use num from it's last known value, rather than resetting it.
That means you're simply tacking another copy of the file on to the end of the array each time.
And, please, if you value the sanity of the people who may have to maintain your code, don't use function names like fN(), they're supposed to be readable :-)
Interestingly enough, this only affects the functions that use the array. I notice that your function which gives you the total and average reads the file itself, despite calling f7() to read it into the array. You may want to choose one method and stick with it.