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;
}
Related
I am writing a program that takes multiple user inputs, and counts how many prime numbers there are, and which number is the greatest and smallest of the inputs. However, I am stuck. when I run the code, it thinks every new input is the greatest number. for example, if I enter 1, 2, 3, 2... It says the greatest number is 2. It takes the last integer inputted and thinks that is the greatest number. I have no started on the lease common number yet, but if I am able to understand how to get the greatest number, I bet I can get the least. Thanks guys!
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
int oldnum = 0;
int userinput=0;
int newnum = userinput;
int greatestnum = 0;
int greatestcounter = 0;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (greatestnum > userinput) {
greatestnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
greatestnum is only assined if it's greater than the user input. Since it's initialized to 0, the if statement,
if (greatestnum > userinput) {
greatestnum = userinput;
}
will be false unless the user input is less than zero. If you want to make it the greatest from all user inputs, flip it to < and move the int greatestnum = 0; to right above the if (begin >= 0) {.
if (greatestnum < userinput) {
greatestnum = userinput;
}
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0,greatestnum = 0,oldnum = 0,userinput = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (userinput > oldnum) {
greatestnum = userinput;
oldnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
Initialize 'oldnum=0' , 'userinput=0' and 'greatestnum=0' outside the loop. And there were some error in logic. If userinput is greater the old num the update greatest num=userinput and oldnum=userinput.
#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
class List{
private:
int A[10];
int i;
public:
List(){
i = 0;
}
void insert(){
int v;
for(int j = 0 ; j < 10 ; j++){
cout << "\nElement you want to insert: (" << i+1 << "). ";
cin >> v;
if(i <= 9){
A[i] = v;
i++;
}
else{
cout << "\nWrong Input" << endl;
break;
}
}
if(i > 9){
cout << "\nYour List Capacity is Full.\n" << endl;
}
}
void display(){
cout << "\n{ ";
for(int j = 0 ; j < i ; j++)
cout << A[j] << " ";
cout << "}\n" << endl;
}
void remove(){
int p;
cout << "\nElement you want to remove (0 - 9): ";
cin >> p;
if (i == 0){
cout << "\nList is empty!\n" << endl;
return;
}
if (p >= 0 && p < i){
for(int j = p ; j < i-1 ; j++)
A[j] = A[j + 1];
i--;
}
}
void size(){
cout << "\nYour list size is: " << i << endl;
}
void checkcapacity(){
int arrSize = sizeof(A)/sizeof(A[0]);
cout << "\nThe Capacity of the array is: " << arrSize << endl;
}
};
int main(){
List l;
int a;
cout << "\t\t\t\t\t\tWelcome to List Program!";
while(a != 4){
int choose;
cout << "\nThe Program have following options:\n1. Insert\n2. Display\n3. Remove\n4. Check Size\n5. Check Capacity\n6. Exit\n\nNote: Your list capacity is 10!";
cout << "\n\nChoose (1 - 5): ";
cin >> choose;
if (choose == 1){
l.insert();
}
else if (choose == 2){
l.display();
}
else if (choose == 3){
l.remove();
}
else if (choose == 4){
l.size();
}
else if (choose == 5){
l.checkcapacity();
}
else if (choose == 6){
a = 4;
}
}
cout << "Thank you for using this program!";
}
I'm using this class in my main function in which I call them but when the user inputs a char or string in the insert function it goes into infinte loop. Int i is my counter and it just contains the size of my array list im just trying to put a check of character that if user input a character is should show an error.
Here's one way to write your insert function
void insert()
{
int v;
for(int j = 0 ; j < 10 ; j++)
{
cout << "\nElement you want to insert: (" << i+1 << "). ";
if (cin >> v)
{
if (i < 10)
{
A[i] = v;
i++;
}
}
else
{
cin.clear(); // clear error
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard any pending input
}
}
if (i >= 10)
cout << "\nYour List Capacity is Full.\n" << endl;
}
The important part is the recovery from bad input. First cin.clear() is called to clear the stream error state, secondly cin.ignore(...) is called to discard any pending input.
More details here
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() )
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 8 years ago.
Improve this question
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)
I'm creating a hangman game. I'm having a problem asking the user to reenter a new guess(char) if they have entered that same one already(these are contained in the letters[] array). I have started with a while loop that asks the user to reenter if "guess" matches one of the chars that stored in the array. Thanks.
void play(string word)
{
string copy = word;
for(int i = 0; i < word.length(); i++)
{
copy[i] = ' ';
}
bool match = false;
bool valid = false;
int chance = 5;
char letters[26];
int counter = 0;
char guess;
while (chance > 0 && match == false)
{
int blanks = 0;
for (int i = 0; i < word.length(); i++)
{
if(copy[i] == ' ')
blanks++;
}
cout << '|';
for(int i = 0; i < word.length(); i++)
{
cout << copy[i] << '|';
}
cout << "\t(There are '" << blanks << "' blanks)" << endl;
cout << "Incorrect letters guessed: ";
for (int i = 0; i<counter; i++)
{
cout << "'" << letters[i] << "' ";
}
cout << "\n\nEnter guess: ";
cin >> guess;
for(int i = 0; i < counter; i++)
{
if(guess == letters[i])
valid = true;
}
while (valid == true)
{
for(int i = 0; i < counter; i++)
{
if(guess == letters[i])
valid = true;
else
valid = false;
}
if (valid)
{
cout << "\n\nAlready tried that one. Enter guess: ";
cin >> guess;
}
}
long find = word.find(guess);
if (find != string::npos)
{
copy[find] = word[find];
for (int i = 0; i < word.length(); i++)
{
if (word[i] == word[find])
{
copy[i] = word[find];
}
}
}
else
{
chance--;
letters[counter] = guess;
counter++;
printMan(chance);
}
if (copy == word)
{
match = true;
}
}
if (match == true)
cout << "\nYou saved a life! You managed to win! Congrats, cheater." << endl;
else
cout << "\nThe man has been hung! You LOSE! The word was '" << word << "', you idiot." << endl;
}
for(int i = 0; i < counter; i++)
{
if(guess == letters[i])
valid = true;
else
valid = false;
}
The problem with this for loop is that after you find a valid guess... you don't stop looping.
You go on and check if letter equals the next value in the loop too - and the next and the next. and valid keeps getting overwritten over and over until you get to the end of the loop - at which time valid equals the value of the check against the last letter in letters.
so your "check guess" code only gets called if guess matches the last letter in letters.
You need to look up how to exit out of a loop at the moment that you find a matching guess.