I trying to create a program that receives and stores information about in a dynamic array of structures. And the program should sort and display the teams above average, average and below avaerage. This is my code so far. . So what I'm doing is I receive the user input the check the input before storing it in dynamic structure array. Then finally I display all the information stored in the struct. Here's the output that i'm currently getting and I'm not sure why i'm getting this negative numbers.any ideas why?
Thanks
How many teams do you want to store? 2
Enter the name of the team 1:Vikings
Enter the team 1 percentage: 90
Enter the name of the team 2:PackersGreen Bay Packers
Enter the team 2 percentage: 80
Above Average :
Vikings 90%
PackersGreen Bay Packers 80%
Average :
5.00136e-317%
None
Below Average :
None
9.25737e-306%
Here's my code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
struct aboveAverage
{
string name9;
double percentage1;
};
struct average
{
string name10;
double percentage2;
};
struct belowAverage
{
string name11;
double percentage3;
};
int numOfteams;
double userInput;
cout << "How many teams do you want to store? ";
cin >> numOfteams;
cin.get();
aboveAverage * arrayOfAboveAverage = new aboveAverage[numOfteams];
average * arrayOfAverage = new average[numOfteams];
belowAverage * arrayOfbelowAverage = new belowAverage[numOfteams];
for (int i = 0; i < numOfteams; i++)
{
start:
int x = i + 1;
string name5;
cout << "Enter the name of the team " << x << ":";
getline(cin, name5);
cout << "Enter the team " << x << " percentage: ";
cin >> userInput;
cin.get();
if (userInput >= 66 && userInput <= 100)
{
arrayOfAboveAverage[i].percentage1 = userInput;
arrayOfAboveAverage[i].name9 = name5;
}
else if (userInput <= 66 && userInput >= 33)
{
arrayOfAverage[i].name10 = name5;
arrayOfAverage[i].percentage2 = userInput;
}
else if (userInput <= 33 && userInput >= 0)
{
arrayOfbelowAverage[i].name11 = name5;
arrayOfbelowAverage[i].percentage3 = userInput;
}
else
{
cout << "Percent cannot be greater than 100" << endl;
goto start;
}
}
cout << "Above Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
{
cout << arrayOfAboveAverage[j].name9 <<" ";
cout << arrayOfAboveAverage[j].percentage1 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
{
cout << arrayOfAverage[j].name10 <<" ";
cout << arrayOfAverage[j].percentage2 <<"%"<<endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Below Average : "<< endl;
for (int k = 0; k < numOfteams; k++)
{
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
{
cout << arrayOfbelowAverage[k].name11 << " ";
cout << arrayOfbelowAverage[k].percentage3 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
delete[] arrayOfAboveAverage;
delete[] arrayOfAverage;
delete[] arrayOfbelowAverage;
return 0;
}
The problem is in the following test
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
When arrayOfAverage is uninitialized (as in your case) name10 is initialized with the default value for a std::string (the empty string) but the value for percentage2 (a double) is undefined.
You test both values with "or", not "and", so if percentage2 is initialized with a positive value (by example: 5.00136e-317) you enter in the true case.
Suggestion: when there is a useful value, the name10 value isn't empty, so ignore percentage2 and modify the test as follows
if ( ! arrayOfAverage[j].name10.empty() )
Same problem with the preceding
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
and the following test
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
My suggestion is to modify they as follows
if ( ! arrayOfAboveAverage[j].name9.empty() )
// ...
if ( ! arrayOfBelowAverage[j].name11.empty() )
Related
My GetMark() function, which is supposed to check for correct range and afterwards return the value, if correct to the given array gets stuck in a infinite loop when a parameter is given outside of the accepted range, before i added the SearchMark() function it worked correctly and looped only until the user finally entered a value in the given range (0 - 100) but now after the first out of range value is given it loops no matter what is entered, I will be thankful for any suggestions. full code:
int GetMark(int ModuleIndex) //user input function
{
bool help;
if (ModuleIndex < 0 || ModuleIndex >100)
{
help = false;
while (help != true)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "hey, that's a invalid value, try again!" << endl;
GetMark(ModuleIndex);
if ((ModuleIndex > 0) &&( ModuleIndex < 101))
{
help = true;
}
}
}
return ModuleIndex;
}
int SearchMark(int A[], int a) //search grades array for numbers of specific grades
{
int i = 0;
int ii = 0;
while (i < 12)
{
if (A[i] == a)
ii++;
i++;
}
cout << "Mark " << a << " was found: " << ii << " times" << endl;
return 0;
}
int main()
{
int marks[12];
int i = 0;
int sum = 0;
int grades[12];
while (i < 12)
{
cout << "enter mark (0 - 100): " << endl;
cin >> marks[i];
GetMark(marks[i]);
sum = sum + marks[i];
if (marks[i] > 69)
{
grades[i] = 1;
}
else if (marks[i] > 59 && marks[i] < 70)
{
grades[i] = 2;
}
else if (marks[i] > 49 && marks[i] < 60)
{
grades[i] = 22;
}
else if (marks[i] > 39 && marks[i < 50])
{
grades[i] = 3;
}
else if (marks[i] < 35)
{
grades[i] = 4;
}
i++;
}
sum = sum / 12;
cout << "your average is: " << sum << endl;
if (sum > 69)
{
cout << "You passed with 1st!" << endl;
}
else if ((sum > 59) && (sum < 70))
{
cout << "You passed with 2i!" << endl;
}
else if ((sum > 49) && (sum < 60))
{
cout << "You passed with 2ii!" << endl;
}
else if ((sum > 39) && (sum < 50))
{
cout << "You passed with 3rd!" << endl;
}
else if (sum < 40)
{
cout << "Your average is too low! You failed." << endl;
}
i = 0;
while (i < 12)
{
if (marks[i] < 35)
{
cout << "Referred in module " << i + 1 << " mark too low." << endl;
}
i++;
}
SearchMark(grades, 1);
SearchMark(grades, 2);
SearchMark(grades, 22);
SearchMark(grades, 3);
SearchMark(grades, 4);
return 0;
}`
That function is overly complicated for what it does. Just loop while the value is bad, and prompt for a new value:
int GetMark(int ModuleIndex) {
while (ModuleIndex < 0 || ModuleIndex > 100) {
std::cout << "Invalid value.\n"
std::cin >> ModuleIndex;
}
return ModuleIndex;
}
Recursion is very handy in theoretical analysis, but in practice it's almost always a mistake.
You need to allow the user to specify a new value of marks[i] / ModuleIndex within GetMarks. After clearing cin, read a new value from cin. You also need to return that value so that main's marks[i] can be updated with that value instead of the original out-of-range value.
Basically what you need to do is remove the recursion from this method and just rely on the while loop. Instead of recalling the function you need to prompt for input again with the failed input and then test the value again to escape the loop.
int GetMark(int ModuleIndex) //user input function
{
bool help;
if (ModuleIndex < 0 || ModuleIndex >100)
{
help = false;
while (help != true)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "hey, that's a invalid value, try again!" << endl;
cout << "enter mark (0 - 100): " << endl;
cin >> ModuleIndex;
if ((ModuleIndex > 0) &&( ModuleIndex < 101))
{
help = true;
}
}
}
return ModuleIndex;
}
It is apparently in you getMark, inside the while loop you are calling getMark recursively with the same invalid ModuleIndex value. So you need to get it from the standard input before recursion. e.g:
int GetMark(int ModuleIndex){
bool help;
if (ModuleIndex < 0 || ModuleIndex > 100){
help = false;
while (help != true){
cout << "enter new ModuleIndex: \n";
cin >> ModuleIndex;
GetMark(ModuleIndex);
// ...
}
return ModuleIndex;
}
Your code is unreadable, in addition you can use class std::vector.
I propose to test this code:
int GetMarkIndex(const std::vector<double>& vMarks, const double Search) {
auto beg{ vMarks.begin() }, end{ vMarks.end() };
while (beg != end && *beg != Search)
++beg;
return beg != end ? beg - vMarks.begin() : -1;
}
int main() {
std::vector<double> marks(5);
int value;
auto i{ 0U };
auto sz{ marks.size() };
while (i != sz) {
std::cout << "Enter marks 1-->100" << std::endl;
if (cin >> value && value > 0 && value < 101) {
marks[i] = value;
++i;
}
else
std::cout << "Invalid input!" << std::endl;
}
for (auto e : marks)
cout << e << ", ";
std::cout << std::endl;
double Search = 15;
auto index{GetMarkIndex(marks, Search)};
(index != -1) ? (std::cout << Search << " Found at index: " << index) : (std::cout << Search << " Not found!" << std::endl);
std::cout << std::endl;
}
The combination of the way you have defined GetMark and the way you use it is flawed.
No matter what you do in GetMark, the value entered in main does not change.
Change GetMark to:
int GetMark()
{
std::cout << "enter mark (0 - 100): " << std::endl;
int mark;
while ( std::cin >> mark )
{
if ( mark >= 0 && mark <= 100)
{
return mark;
}
std::cout << "Invalid value " << mark << std::endl;
std::cout << "enter mark (0 - 100): " << std::endl;
}
// Unable to read.
// Throw exception, or exit with an error message.
}
and change its usage. Instead of
cout << "enter mark (0 - 100): " << endl;
cin >> marks[i];
GetMark(marks[i]);
use
marks[i] = GetMark();
A working version of GetMark:
int GetMark()
{
std::cout << "enter mark (0 - 100): " << std::endl;
std::string line;
while ( getline(std::cin, line) )
{
std::istringstream str(line);
int mark;
if ( str >> mark )
{
if ( mark >= 0 && mark <= 100)
{
return mark;
}
}
std::cout << "Invalid input: " << line << std::endl;
std::cout << "enter mark (0 - 100): " << std::endl;
}
// Unable to read.
// Throw exception, or exit with an error message.
return 0;
}
Live Demo.
I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();
We're only interested in the #'s in the range [0,100]. There may be number outside the range [0, 100], but they aren't part of our calculation (i.e numbers below 0 and above 100 can be inputted but will be ignored in the calculations and counters).
Assume we assign ABCDF as
[85,100]: A
[75,85): B
[65,75): C
[55,65): D
[0,55): F
For each of the five letter grades, output the number of scores with that grade, and also, if the number of scores wasn't 0, output the average score with that grade. Also, if the number of valid scores (in [0, 100]) wasn't 0, output the average of all the scores
I am having trouble with this looping question. When I input multiple scores, it loops them incorrectly and outputs two sets of grades for each input rather than the example answer shown above. Also I am not sure if my break is placed correctly to exit the program when a word is inputted. Any help will be greatly appreciated!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
for (scores; cin >> scores;){
if (scores > 85 && scores <= 100){
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75){
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65){
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55){
grade = 'D';
countD++;
sumD += scores;
}
else{
grade = 'F';
countF++;
sumF += scores;
}
if (!cin){
break;
}
if (countA == 0){
cout << "# A's: 0 " << endl;
}
else {
cout << "# A's: " << countA << " Average = " << sumA/countA << endl;
} if (countB == 0){
cout << "# B's : 0 " << endl;
}
else{
cout << "# B's: " << countB << " Average = " << sumB /countB << endl;
} if (countC == 0){
cout << "# C's: 0 " << endl;
}
else{
cout << "# C's: " << countC << " Average = " << sumC /countC << endl;
} if (countD == 0){
cout << "# D's: 0 " << endl;
}
else {
cout << "# D's: " << countD << " Average = " << sumD /countD << endl;
} if (countF == 0){
cout << "# F's: 0 " << endl;
}
else {
cout << "# F's: " << countF << " Average = " << sumF /countF << endl;
}
}
TL;DR version: Closing brace on the for loop was missing. Loop never ended and caused OP's output code to also loop.
Long version:
Here is working code. The stuff I changed is marked with comments.
#include <iostream> //removed a bunch of unused includes.
using std::cin; // including all of namespace::std is overkill and often
using std::cout; // leads to hard-to-solve bugs. Only use what you need
using std::endl;
int main()
{
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
// for (scores; cin >> scores;){
while (cin >> scores) // cleaner
{
if (scores > 85 && scores <= 100)
{
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75)
{
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65)
{
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55)
{
grade = 'D';
countD++;
sumD += scores;
}
else
{
grade = 'F';
countF++;
sumF += scores;
}
// this test is made redundant by the loop condition
// if (!cin)
// {
// break;
// }
} // this was missing. The loop kept going and included all of
// the following code in the loop.
if (countA == 0)
{
cout << "# A's: 0 " << endl;
}
else
{
cout << "# A's: " << countA << " Average = " << sumA / countA << endl;
}
if (countB == 0)
{
cout << "# B's : 0 " << endl;
}
else
{
cout << "# B's: " << countB << " Average = " << sumB / countB << endl;
}
if (countC == 0)
{
cout << "# C's: 0 " << endl;
}
else
{
cout << "# C's: " << countC << " Average = " << sumC / countC << endl;
}
if (countD == 0)
{
cout << "# D's: 0 " << endl;
}
else
{
cout << "# D's: " << countD << " Average = " << sumD / countD << endl;
}
if (countF == 0)
{
cout << "# F's: 0 " << endl;
}
else
{
cout << "# F's: " << countF << " Average = " << sumF / countF << endl;
}
}
Your question is a bit confusing, I assume your main issue is the output part. Currently your code produces this.
As you see we get intermediate output, after every score entered. To change that the loop needs to be split into two loops: One for input, and one for output that runs after the first:
while (/* we get scores */) {
// update the counters and sums
}
for (/* every score */) {
// print count and average
}
To generate the output in a loop you need to store your data in some "loopable" way. Currently you have multiple local variables. Changing that to an array (indexed by the respective grade) allows us to loop over the data:
unsigned counter[5];
double sum [5];
// A -> 0, B -> 1, ..., F -> 4
for (std::size_t it = 0; it < 5; ++it) {
// use sum[it] and counter[it]
}
But raw arrays (as raw pointers) are evil - only use them when absolutely necessary - we use std::array from the standard library. And to ease iteration and improve logical encapsulation it's good to keep sum and count of each grade together:
struct grade_info {
unsigned count = 0;
double sum = 0;
};
// ... later in the main function
std::array<grade_info, 5> grades;
// input
for (auto const & grade : grades) { // C++11 shorthand to iterate over a collection
// use grade.count and grade.sum
}
Concerning your input:
for (scores; cin >> scores;){
This does the right thing, but is a bit strange. Since scores will only be used inside that loop instead of declaring it as local variable of main we only declare it inside the loop:
for (double score; // only a single score is in that variable at any time
cin >> score; // ends the loop on eof or failure to convert to double (when text got entered)
// no step instructions, the above check does that already
) {
Now there's also no need to test cin inside the loop. The operator>> returns (a reference to) its first argument, which is cin, so the test in the for loop already tests cin, no need for if (! cin) { break; }.
Then you have code like this
grade = 'A';
when you never use the value stored in grade. Just remove that.
Last but not least your input validation isn't working (the 101 in my test case is treated as grade B):
if (scores > 85 && scores <= 100) {
// scores between (85, 100]
}
// scores is either <= 85 OR > 100
else if (scores > 75){
// scores is in (75, 85] OR > 100
}
Ideally you should keep input validation and business logic separated:
if (not input_is_valid(score)) {
continue; // the loop
}
// business logic, assuming valid input
So, the final code could be
#include <iostream>
#include <array>
struct grade_info {
unsigned count = 0;
double sum = 0;
char const name;
grade_info(char n) : name(n) {
}
};
bool input_is_valid(double score) {
return (score >= 0) and (score <= 100);
}
std::size_t score_to_grade_index(double score) {
if (score >= 85) {
return 0;
} else if (score >= 75) {
return 1;
} else if (score >= 65) {
return 2;
} else if (score >= 55) {
return 3;
} else {
return 4;
}
}
int main(int, char**) {
std::array<grade_info, 5> grades {'A', 'B', 'C', 'D', 'F'};
for (double score; std::cin >> score;) {
if (not input_is_valid(score)) {
continue;
}
auto index = score_to_grade_index(score);
++(grades[index].count);
grades[index].sum += score;
}
for (auto const & grade : grades) {
std::cout << "# " << grade.name << ": "
<< grade.count;
if (grade.count > 0) {
std::cout << " avg: " << (grade.sum / grade.count);
}
std::cout << std::endl;
}
return 0;
}
Live here
while (deckSize > 2)
{
one_Card = card_deck.back();
card_deck.pop_back();
two_Card = card_deck.back();
card_deck.pop_back();
three_Card = card_deck.back();
card_deck.pop_back();
oneCard_Name = card_name(one_Card);
twoCard_Name = card_name(two_Card);
threeCard_Name = card_name(three_Card);
oneCard_Suit = card_suit(one_Card);
twoCard_Suit = card_suit(two_Card);
threeCard_Suit = card_suit(three_Card);
oneCard_Rank = card_rank(one_Card);
twoCard_Rank = card_rank(two_Card);
threeCard_Rank = card_rank(three_Card);
bool between1 = (oneCard_Rank < threeCard_Rank && threeCard_Rank < twoCard_Rank);
bool between2 = (twoCard_Rank < threeCard_Rank && threeCard_Rank < oneCard_Rank);
cout << "Here are your two cards: " << endl;
cout << setw(10) << oneCard_Name << " of " << oneCard_Suit << setw(20) << twoCard_Name << " of " << twoCard_Suit << endl;
cout << "Do you think the next card will lie between these? (y/n): ";
cin >> user_input;
cout << endl << endl;
cout << "Here is your next card: " << endl;
cout << setw(10) << threeCard_Name << " of " << threeCard_Suit << endl << endl << endl;
count++;
if(user_input == "y" || user_input == "yes" || user_input == "Yes" || user_input == "Y")
{
if(between1 || between2)
{
cout << "You win!" << endl;
win++;
}
else
{
cout << "You lose!" << endl;
lose++;
}
}
else
{
if(between1 || between2)
{
cout << "You lose!" << endl;
lose++;
}
else
{
cout << "You win!" << endl;
win++;
}
}
}
cout << "You have played this game " << count << " times and you have won: " << win << " and lost " << lose << endl;
return 0;
}
These are the two subprograms that shuffle and initialize the deck
void initDeck(vector<int> &card_deck)
{
int i;
for(i = 0; i <= 51; i++)
{
card_deck[i] = i;
}
}
void shuffleDeck(vector<int> & card_deck)
{
int n;
for(n = 51; n >= 0; n--)
{
int i = randomize();
int temp = card_deck[i];
int temp2= card_deck[n];
card_deck[n] = temp;
card_deck[i] = temp2;
}
}
After when I run the program it allows me to run it, but when I reach to the number less than the condition in the while loop it just gives me an error, and does not finish the program. I had this error earlier and fixed it, so I have a basic understanding of what the error means. From my knowledge it is trying to collect numbers past the vector length. However this time I don't see my error at all.
deckSize is not being set/updated anywhere. It should rather be card_deck.size()
You should use push_back and emplace for the type vector like this:
void initDeck(vector<int> &card_deck){
int i;
for(i = 0; i <= 51; i++)
{
card_deck.push_back(i);
}
}
Take a see to this link
Try this:
void initDeck(vector<int> &card_deck)
{
int i;
for(i = 0; i <= 51; i++)
{
card_deck.push_back(i);
}
}
void shuffleDeck(vector<int> & card_deck)
{
int n;
for(n = 51; n >= 0; n--)
{
int i = randomize();
int temp = card_deck[i];
int temp2= card_deck[n];
card_deck[n] = temp;
card_deck[i] = temp2;
}
}
For generating random number see this and this. Or you can find other solution that is more reliable.
My string d is displayed empty (not even a space) on my console, this is getting me confused since I initialized it to "NULL" and I am trying to assign a new value to it which isn't a empty value.
int main(){
string user_String[99];
int user_Input = 0;
cout << "Please insert up to one hundred Strings: ";
cin >> user_Input;
//Check for range
bool check = false;
while( check == false){
if (user_Input < 1 || user_Input >100){
cout << "Please insert up to one hundred Strings: ";
cin >> user_Input;}
else{
check = true;
break;}
}
//User input
cout <<"Please enter string"<< endl;
for (int counter = 0; counter < user_Input; counter++){
int counter2 = counter + 1;
cout << "Enter String " << counter2 << ": ";
cin >> user_String[counter];
}
//Loopig for most letters
string c = "NULL";
for(int counter = 0; counter < user_Input; counter++){
//Making Sure Coun doesn't go out of range
int coun = 0;
if (counter < user_Input){
coun = counter +1;}
else{
coun = counter;
}
string a = user_String[counter];
string b = user_String[coun];
if (a.length() < b.length() && c == "NULL"){
c = b;
}
if(a.length() < b.length() && c!="NULL" && c.length() < b.length()){
c = b;
}
else{
continue;
}
}
cout << "The string "<< c <<" have the most letters." << endl;
//Looping for least letters
string d = "NULL";
for(int counter = 0; counter < user_Input; counter++){
//Making Sure Coun doesn't go out of range
int coun = 0;
if (counter < user_Input){
coun = counter +1;}
else{
coun = counter;
}
string a = user_String[counter];
string b = user_String[coun];
if (a.length() > b.length() && d == "NULL"){
d = b;
}
if(a.length() > b.length() && d!="NULL" && d.length() > b.length()){
d = b;
}
else{
continue;
}
}
cout << "The string " << d <<" have the least letters." << endl;
system("pause");
return 0;
}
You allow the user to enter up to 100 strings, but your array can only hold up to 99 strings. If they actually enter 100 strings, the last string will corrupt memory, assume your code does not crash altogether.
Also, your letters loops have some faulty logic in them. if (counter < user_Input) will always be true, so coun will always be counter+1 and thus exceed the bounds of the array when counter reaches the end of the array. Also, your loops are unnecessarily complex for what they are trying to do.
Try this instead:
int main()
{
string user_String[100];
int user_Input;
do
{
cout << "Please enter the number of Strings (1-100): ";
if (cin >> user_Input)
{
if ((user_Input >= 1) && (user_Input <= 100))
break;
}
else
cin.clear();
}
while (true);
for (int counter = 0; counter < user_Input; ++counter)
{
cout << "Enter String " << counter + 1 << ": ";
cin >> user_String[counter];
}
string b = user_String[0];
for(int counter = 1; counter < user_Input; ++counter)
{
string a = user_String[counter];
if (a.length() > b.length())
b = a;
}
cout << "The string " << b << " has the most letters." << endl;
b = user_String[0];
for(int counter = 1; counter < user_Input; ++counter)
{
string a = user_String[counter];
if (a.length() < b.length())
b = a;
}
cout << "The string " << b <<" has the least letters." << endl;
system("pause");
return 0;
}
With that said, you can get rid of the array altogether and merge the loops together:
int main()
{
string user_String;
int user_Input;
do
{
cout << "Please enter the number of Strings: ";
if (cin >> user_Input)
{
if (user_Input >= 1)
break;
}
else
cin.clear();
}
while (true);
string fewestLetters, mostLetters;
for (int counter = 1; counter <= user_Input; ++counter)
{
cout << "Enter String " << counter << ": ";
cin >> user_String;
if (counter == 1)
{
mostLetters = user_String;
fewestLetters = user_String;
}
else
{
if (user_String.length() > mostLetters.length())
mostLetters = user_String;
if (user_String.length() < fewestLetters.length())
fewestLetters = user_String;
}
}
cout << "The string " << mostLetters << " has the most letters." << endl;
cout << "The string " << fewestLetters << " has the least letters." << endl;
system("pause");
return 0;
}