I'm trying to devise a function that randomly selects three of the five strings and displays them on the screen. Here's what I have so far. It runs but nothing prints to the screen.
#include "BoxOfProduce.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
BoxOfProduce::BoxOfProduce()
:choices{""}, bundles{""}
{
}
vector<string> BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}
#ifndef BOXOFPRODUCE_H
#define BOXOFPRODUCE_H
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class BoxOfProduce
{
public:
BoxOfProduce();
string getBundles();
void setBundles(string b);
vector<string> randomize();
private:
string bundles[3];
const string choices[5];
string random;
};
#endif // BOXOFPRODUCE_H
#include <iostream>
#include "BoxOfProduce.h"
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>
using namespace std;
int main()
{
srand(time(0));
BoxOfProduce bo;
bo.randomize();
auto vector<string> randomResult = bo.randomize();
for (const auto& result : randomResult){
cout << result << endl;
}
}
I have updated my code now and still no print output. Although I am getting an error:
error: range-based 'for' loops are not allowed in C++98 mode
I have never worked with auto before. So any help on this would be appreciated.
Your code should not compile. g++ emits the following error:
return random;
error: could not convert ‘random’ from ‘long int (*)()throw ()’
The random variable is local to your for-body. You should give it a greater scope:
string random;
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
To produce the 3 results, you need to return a vector of string like
#include<ctime>
#include<cstdlib>
#include<string>
#include<memory>
#include<vector>
#include<iostream>
using namespace std;
std::vector<string> randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
std::vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}
int main()
{
srand(time(0));
randomize();
std::vector<string> randomResult = randomize();
for (std::vector<string>::const_iterator iter = randomResult.begin(), iterEnd = randomResult.end();
iter != iterEnd; ++iter)
cout << *iter << endl;
return 0;
}
The scope of string random is only inside the for loop in your code.
try this:
string BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
string random = "";
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
}
int main()
{
srand(time(0));
BoxOfProduce bundle1;
bundle1.randomize();
cout << bundle1.randomize() << endl;
}
The code you provided shouldn't even compile. Try this:
string BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};
string random;
for(int i = 0; i < 3; i++)
{
random = choices[rand() % 5];
}
return random;
}
int main()
{
srand(time(0));
BoxOfProduce bundle1;
bundle1.randomize();
cout << bundle1.randomize() << endl;
}
The braces { } define a scope. After that scope, the variables you define inside it are destroyed. So you should define that variable before you start that scope.
Probably the reason it compiled is that you already have another variable string random inside the body of the class BoxOfProduce. So you either define that string random outside the scope, like I did, or you just remove the string before random, and then the compiler will use the variable from the class body.
Related
Forgive my ignorance. I'm still at the beginning of C++, and am having a hard time grasping the language, since it is my first.
How would I call the strings or int in a function into another function so I would be able to separate the different processes required for the program?
I'm really sorry if it's messy, from my understanding the code should work, but it is displaying nothing on the main.cpp file.
This is a full house probability checker. I'm supposed to run a bunch of rounds and deal out five cards and check if they are a full house. Please tell me what I can improve on, and what I lack in my understanding.
class.cpp
#include <iostream>
#include "Class.h"
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void shufflewell()
{
srand(time(0));
int deck[52];
int i;
// deck shuffling
for(i=0; i<52; i++)
{
int j = rand() % 52;
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void DisplayCard ()
{
void shufflewell();
int i;
int deck[52];
string suitnames[4]={"spades", "diamonds", "clubs", "hearts"};
string ranknames[13]={"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
int suitnumber = deck[i] / 13; // 0 - 3
int rank = deck[i] % 13;
cout << ranknames[rank] << " of " << suitnames[suitnumber] << endl;
// Get the rank of the first 5 cards
int R[5]; // = {4, 7, 6, 3, 5}; // rank of the first 5 cards
int S[5];
for(i=0; i<5; i++)
{
R[i] = deck[i]%13;
S[i] = deck[i]/13;
}
cout << ranknames[R[i]] << " of " << suitnames[S[i]];
return DisplayCard();
}
// Deals five random cards to player
void dealHand()
{
for(int i = 0; i < 5; i++)
{
DisplayCard();
cout << ranknames[R[i]] << " of " << suitnames[S[i]];
}
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "Class.h"
using namespace std;
int main()
{
cout << "Full house probabilty checker";
void DisplayCard();
return 0;
}
Class.h
#ifndef Class.h
#define Class.h
#include <iostream>
#include <string>
using namespace std;
class cards
{
public:
int i;
int deck[52];
std::string suitnames;
std::string ranknames;
void shufflewell();
void DisplayCard();
void dealHand();
};
#endif // Class
Since C++ is your first language I would suggest reading up on on proper syntax form. Things like calling functions, creating classes and declaring member functions to name a few.
In C++ class member functions are conventionally implemented using a declaration:
// class.h
class cards
{
public:
/* ... */
void DisplayCard();
};
Definition:
// class.cpp
#include "class.h"
void cards::DisplayCard()
{
/* ... */
}
And get called like this:
class_Instance.DisplayCard();
In addition, you are calling DisplayCard from within itself:
void DisplayCard()
{
/* ... */
return DisplayCard();
}
Which causes a stackoverflow - function being executed an exceeding amount of times.
Here are a few resources on how classes and objects are created and used in C++:
https://www.programiz.com/cpp-programming/object-class
https://www.w3schools.com/cpp/cpp_classes.asp
https://cplusplus.com/doc/tutorial/classes/
I'm working on an assignment to create a class called StringBuilder that is used for fast string concatenation. I'm supposed to store strings in a dynamic array and have methods such as Append(string) which adds a new string to the dynamic array. The method I'm currently struggling with is GetString() that creates a single string on the heap that is the length of all the strings in the dynamic array that have been added thus far.
the code I have so far is:
okay my main problem is my GetString() function prints out hello over and over again until I force quit the program in Xcode. I don't understand what inside that method is making that happen.
My header file:
#pragma once
#include <string>
using namespace std;
class StringBuilder
{
public:
StringBuilder();
//~StringBuilder();
void GetString();
void AppendAll(string*, int);
void Length();
void Clear();
void Append(string userString);
void DoubleArray(string*& allWords, int newCapacity);
private:
string* p_array;
int capacity = 5;
};
my .cpp file :
#include "StringBuilder.hpp"
#include <iostream>
#include <string>
using namespace std;
----------
void StringBuilder::Append(string userString)
{
int nextWordPosition = 0;
for(int i=0; i < capacity ; i++)
{
p_array[i] = userString;
cout << p_array[i] << endl;
nextWordPosition +=1;
if(capacity == nextWordPosition)
{
capacity *=2;
DoubleArray(p_array, capacity * 2);
}
}
nextWordPosition++;
}
void StringBuilder::DoubleArray(string*& allWords, int newCapacity)
{
string* p_temp = new string[newCapacity];
for(int i =0; i < newCapacity / 2; i++)
{
p_temp[i] = allWords[i];
}
delete[] allWords;
allWords = p_temp;
}
void StringBuilder:: GetString()
{
for(int i=0; i < capacity ; i++)
{
cout << p_array[i]<< endl;
}
}
my main.cpp file :
#include <iostream>
#include <string>
#include "StringBuilder.hpp"
using namespace std;
int main()
{
string testString = "hello";
string test = "world!";
StringBuilder Builder1;
Builder1.Append(testString);
Builder1.Append(test);
Builder1.GetString();
return 0;
}
Tell me how to create different strings in one pointer string like array.
see following two program. 1st one give an errors. what is wrong here?
Kindly correct it.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string *j={"nilesh",
"rohit",
"samir",};
cout<<j<<endl;
}
#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = {"Zara Ali","Hina Ali","Nuha Ali","Sara Ali",};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Write simply
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s[] = { "nilesh", "rohit", "samir", };
for ( const string &t : s ) cout << t << endl;
}
Also instead of the array you could use standard class std::vector<std::string>
For example
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> v = { "nilesh", "rohit", "samir", };
for ( const std::string &s : v ) std::cout << s << std::endl;
}
Why not try it in this way ?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string j[]={"nilesh",
"rohit",
"samir"};
cout<<j<<endl;
}
Printing j directly wont print all the three names. You need to print j[0], j[1] ...
I've been recently working on a program which consists basically of 24 variations of one function(below). Everything gets executed perfectly apart from the part where I try to compare functions(with eachother). I found out that it is possible to be done by writing 24 if-else statements, yet I am certain there is a shorter way. I've also tried with vectors but no luck for now. Thanks for any help!
one of 24 functions:
int funk1()
{
ifstream myfile ("file.txt");
string line;
int i;
class1 obj1;
obj1.atr1= "Somename";
obj1.atr2="GAATTC";
while (getline(myfile, line))
{
i = countSubstring(line, obj1.atr2);
obj1.sum += i;
};
cout<<obj1.sum<<": "<<obj1.atr1<<"\n";
return obj1.sum;
}
The main function:
int main(){
funk1();
funk2();
funk3();
funk4();
funk5();
funk6();
funk7();
funk8();
funk9();
funk10();
funk11();
funk12();
funk13();
funk14();
funk15();
funk16();
funk17();
funk18();
funk19();
funk20();
funk21();
funk22();
funk23();
funk24();
//This is one way to do it
if (funk18() > funk1())
{
cout<<funk18<<" is the biggest";
}
//...
}
Here is a clean and elegant c++11 solution:
#include <iostream>
#include <functional>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
using MyFunc = std::function<int()>;
int f1() { return 1; }
int f2() { return 15;}
int f3() { return 3; }
int main() {
std::vector<MyFunc> my_functions = {f1, f2, f3};
int max = std::numeric_limits<int>::min();
for (auto const &f : my_functions) {
max = std::max(max, f());
}
cout << max << endl;
return 0;
}
if you want to store the results from functions instead, you could do:
std::vector<int> my_results;
my_results.reserve(my_functions.size());
for (auto const &f : my_functions) {
my_results.push_back(f());
}
auto max_it = std::max_element(std::begin(my_results), std::end(my_results));
cout << *max_it << endl;
I'm trying to do an insertion sort on a vector of baseball pitchers I created yesterday with help from a previous post. I want to sort the pitchers in ascending order by ERA1. I have gotten the insertion sort to work in the past for a set of integers. I think I have a syntax error in my code for the insertion sort. Up until trying to add the insertion sort this program was working well. I get an error - expected unqualified id before [ token. Thanks in advance for any help.
#ifndef Pitcher_H
#define Pitcher_H
#include <string>
#include <vector>
using namespace std;
class Pitcher
{
private:
string _name;
double _ERA1;
double _ERA2;
public:
Pitcher();
Pitcher(string, double, double);
vector<Pitcher> Pitchers;
string GetName();
double GetERA1();
double GetERA2();
void InsertionSort(vector<Pitcher>&);
~Pitcher();
};
#endif
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
Pitcher::Pitcher()
{
}
Pitcher::~Pitcher()
{
}
string Pitcher::GetName()
{
return _name;
}
Pitcher::Pitcher(string name, double ERA1, double ERA2)
{
_name = name;
_ERA1 = ERA1;
_ERA2 = ERA2;
}
double Pitcher::GetERA1()
{
return _ERA1;
}
double Pitcher::GetERA2()
{
return _ERA2;
}
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
void InsertionSort(vector<Pitcher> Pitchers&);
using namespace std;
int main()
{
vector<Pitcher> Pitchers;
cout << "Pitcher" << setw(19) << "Item ERA1" << setw(13) <<
"Item ERA2\n" << endl;
Pitcher h2("Bob Jones", 1.32, 3.49);
Pitchers.push_back(h2);
Pitcher h3("F Mason", 7.34, 2.07);
Pitchers.push_back(h3);
Pitcher h1("RA Dice", 0.98, 6.44);
Pitchers.push_back(h1);
for(unsigned i = 0; i < Pitchers.size(); ++i)
{
cout << setw(19);
cout << left << Pitchers[i].GetName() << "$" <<
setw(10) << Pitchers[i].GetERA1() <<
right << "$" << Pitchers[i].GetERA2() << "\n";
}
cout << endl;
//------------------------------------------------------
InsertionSort(Pitchers);
//Now print the numbers
cout<<"The numbers in the vector after the sort are:"<<endl;
for(int i = 0; i < Pitchers.size(); i++)
{
cout<<Pitchers[i].GetERA1()<<" ";
}
cout<<endl<<endl;
system("PAUSE");
return 0;
}
void InsertionSort(vector<Pitcher> &Pitchers)
{
int firstOutOfOrder = 0;
int location = 0;
int temp;
int totalComparisons = 0; //debug purposes
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitcher.GetERA1([firstOutOfOrder]) < Pitcher.GetERA1[firstOutOfOrder - 1])
{
temp = Pitcher[firstOutOfOrder];
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
Pitcher.GetERA1[location] = temp;
}
}
cout<<endl<<endl<<"Comparisons: "<<totalComparisons<<endl<<endl;
}
Here:
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitchers[firstOutOfOrder].GetERA1() < Pitchers[firstOutOfOrder-1].GetERA1())
{ //^^^your way was not right, should first access the object then
//access member function
temp = Pitcher[firstOutOfOrder];
//^^^should be Pitchers, similar errors below
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
//^^^similar error as inside if condition
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
//^^^similar error as inside if condition
Pitcher.GetERA1[location] = temp;
//^^similar error as in if condition and name error
}
}
Meanwhile, you put the InsertionSort declaration as a member of the Pitcher class
public:
.
.
void InsertionSort(vector<Pitcher>&);
and you also declare the same function inside main,
void InsertionSort(vector<Pitcher> Pitchers&);
//should be vector<Pitcher>& Pitchers
using namespace std;
int main()
the member function probably should be removed in your case. InsertionSort is not a responsibility of your Pitcher class.
Unless this is homework, you're better off using the build in sort from
<algorithm>