Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I either get a infinity loop, 0, or 9. The question reads as follows:
Create a for loop that compares the two strings starting from index 0. For each match, add one point to user score Upon a mismatch, exit the loop using a break statement.
int main() {
string simonPattern;
string userPattern;
int userScore = 0;
int i = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
/* Your solution goes here */
cout << "userScore: " << userScore << endl;
return 0;
}
Some of my tries:
for ( i = 0; simonPattern <= userPattern; ++i ) {
while( simonPattern.at(0) == userPattern.at(0) ) {
++userScore;
if( simonPattern.at(0) != userPattern.at(0) ){
break;
}
}
while ( simonPattern.at(1) == userPattern.at(1) ) {
++userScore;
if( simonPattern.at(1) != userPattern.at(1) ){
break;
}
So until 9.
Another one:
for (int i=0;i < simonPattern.length(); ++i) {
userScore = i ; }
Can't understand what you tried to do in your first approach.
Will modify your second approach here a bit, by adding comparision in the loop body for when to increment score and when to exit from loop, and also changing the loop termination condition a bit.
Approach
We are using the variable userScore to keep track of score of user. Also storing length of the two strings in variables simonPatternLength and userPatternLength to keep track of when one ends.
For the indices of the strings starting from 0, till one of them ends do the following -
1. If current index is equal in both increase userScore by 1
2. else upon mismatch break out of loop
Code
int main() {
string simonPattern;
string userPattern;
int userScore = 0;
int i = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
/* Your solution goes here */
int simonPatternLength = simonPattern.size();
int userPatternLength = userPattern.size();
for(i = 0; i < simonPatternLength && i < userPatternLength; ++i){
if(simonPattern[i] == userPattern[i]){
userScore++;
}
else{
break;
}
}
cout << "userScore: " << userScore << endl;
return 0;
}
Related
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 2 years ago.
Improve this question
I have a c-string that looks something like ABBBCACACACBA and I'm supposed to create a function that deletes the duplicate characters so I end up with ABC. I created a nested for loop that replaces every letter that matches the letter in the outer loop with a \0 and increments a counter that keeps track of the repeats. I'm getting -1 as the amount of repeats that should be documented, and from checking it spits out ABBC instead of ABC. I'm stumped, any ideas?
for (int i = 0; i < SIZE; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (letter[i] == letter[j])
{
letter[j] = '\0';
repeatCounter++;
}
}
}
It is not enough to just replace duplicates with '\0', you have to actually remove them from the string and shift the remaining characters down. Try something more like this:
int size = SIZE, i = 0;
while (i < size)
{
int j = i + 1;
while (j < size)
{
if (letter[j] == letter[i])
{
for (int k = j + 1; k < size; k++)
{
letter[k-1] = letter[k];
}
letter[--size] = '\0';
repeatCounter++;
continue;
}
j++;
}
i++;
}
Live Demo
Here's a simple example which does what you want. It uses std::string to store the output. You can copy-n-paste the code here to test and run. Look into using std::string as it has functions which will make your life easy.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input("ABBBCACACACBA");
string output;
for(size_t i = 0; i < input.size(); i++)
{
if(output.find(input[i]) == string::npos)
{
output += input[i];
}
}
cout << "Input: " << input << endl;
cout << "Output: " << output << endl;
return 0;
}
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 5 years ago.
Improve this question
I'm having some trouble with the code that I've put below. The void functions seem to be fine, but they aren't working. I'm not sure what I've done wrong, so any help is appreciated. Also, I don't know how to use an if statement to call in questions from an infile for two players, as shown below this. Please, I have to turn it in at 11pm 12/3 and any help is appreciated. I've already been working on it for 5 hours now
if statement here to display odd number of questions to player1 and even number of questions to player2, make sure to add the correct score for respective player by calling the function upDateScoreDouble
void getHistory (playerHistory pHist[], int loopy, ifstream& inQuest)
{
int i = 0 ;
loopy = 22 ;
while( i < loopy, i++)
{
inQuest >> pHist[i].alias1 ;
inQuest >> pHist[i].score ;
inQuest >> pHist[i].difficulty ;
inQuest >> pHist[i].date ;
}
return ;
}
void bubblesort (playerHistory pHist[], int length)
{
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < length - j; i++) {
if (pHist[i].score > pHist[i + 1].score) {
tmp = pHist[i].score;
pHist[i].score = pHist[i + 1].score;
pHist[i + 1].score = tmp;
swapped = true;
}
}
}
return ;
}
///3.3.6 create a loop to call the getQuestion function for each question
for(int loopy=1; loopy<=numQuestions; loopy++)
{
///3.3.6.2 getQuestion function call
getQuestion(gameQ, numQuestions, inQuest) ;
///3.3.6.1 if statement here to display odd number of questions to player1 and even number of questions to player2
///make sure to add the correct score for respective player by calling the function upDateScoreDouble
if(loopy < numQuestions)
{
inQuest >> gameQ[loopy].question;
cout << gameQ[loopy].question ;
cout << gameQ[loopy].answer ;
cout << gameQ[loopy].ans1 ;
cout << gameQ[loopy].ans2 ;
cout << gameQ[loopy].ans3 ;
cout << gameQ[loopy].ans4 ;
}
} ///end of for loop of number of questions
In the getHistory function it looks like you want a for loop instead.
Because the expression i < loopy, i++ evaluates i < loopy and then throws away the result.
Instead the condition of the loop is i++, and since it's 0 in the first iteration the result is false and the loop never happens.
Read more about the comma-operator in e.g. this reference.
You probably want something like
for (int i = 0; i < 22; ++i) { ... }
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'm struggling with an assignment for my class where we have to take input from the user into a char array (word) and take out the duplicates in the word inputted if needed. Comparing the array of the modified array (word) with the alphabet array (abc) to remove the repeated letters from the list. Once the duplicates are removed then just output the modified word followed by the new form of the alphabet into the newAbc array.
For example:
The word HELLO would first become HELO then after comparing to the alphabet the end output from the new array should be HELOABCDFGIJKMNPQRSTUVXYZ.
I'm stuck more on the for loops comparing the new word to the alphabet really.
char word[20], newAbc[40] = { '\0' };
char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int i = 0, b = 1, n = 0, leng, dup;
//dup counts up the repeats but is established in the first portion of the program but i've excluded it as it works perfectly.
cout << "Please enter a word: ";
cin >> word;
leng = strlen(word);
b = 0;
n = leng - dup;
i = 0;
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b])
{
newAbc[n] = abc[b];
n++;
}
}
}
for (i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;
}
I'd appreciate any kind of insight on my mistakes.
The major problem for crash is that you are changing n inside for loop for iterating in newAbc. And your if condition will be true for at least 25 times so incrementing n by 25(minimum) in each iteration resulting in accessing out of bound memory(SEG-FAULT).
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b]) // this condition is not correct
{ // this will be true atleast 25 times
newAbc[n] = abc[b]; // wrong memory access
n++; // here is the problem
}
}
}
Assuming that your duplicate counting works fine, below are the changes required:-
char word[20];
// FIXME: your new array should not contain no duplicate so size can be 27
char newAbc[40] = {'\0'};
// FIXME: simply can be char abc[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
cout << "Please enter a word: ";
cin >> word;
// dup counts up the repeats but is established in the first portion of
// the program but i've excluded it as it works perfectly.
// Lets say word = "HELLO"; so dup = 1, and newArray, should have "HELO"
memcpy(newAbc, "HELO", 4); // from your excluded part of code
int dup = 1; // from your excluded part of code
int leng = strlen(word); // length of input word
int n = leng - dup; // char remained to be inserted
// iterator for new array(newAbc)
int c = n; // n elements are already there
// Just reversed your loop
for (int b = 0; b < 27; b++)
{
int found = 0;
for (int i = 0; i < n; i++)
{
if (newAbc[i] == abc[b])
{
found = 1;
break;
}
}
if (!found)
{
newAbc[c] = abc[b];
c++;
}
}
for (int i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;
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
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Complicated question, probably simple answer. So the program I need to make cannot include any library other than String, iostream, and vector. I need to create a program that has 3 functions. One that creates an integer vector, one that reverses a vector, and one that prints a vector. In order to take in values I need to use getline to intake a string, if the string states quit, we stop putting new values into it. Other wise we need to test if its an integer(positive or negative) and add it to the vector. My code is starting to get complicated so I really need some help. Below is what i have so far. I'm also using Visual Studio, if that matters. Thanks for any help in advance! The question I have is when I run the program, it will only output the first digit. I don't know why and would like to know what I'm doing wrong.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> CreateVector()
{
string tempvariable;
bool quit = false;
vector<int> userinput;
cout << "Please enter in an integer, type 'quit' to exit " << endl;
while (!quit)
{
getline(cin, tempvariable);
if (tempvariable == "quit")
quit = true;
else
{
bool isaninteger = true;
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
continue;
else
{
cout << "You entered in an incorrect option, please enter in a correct option" << endl;
cin.clear();
cin.ignore();
isaninteger = false;
break;
}
}
if (isaninteger)
userinput.push_back(stoi(tempvariable));
cout << "Please enter in an integer, type 'quit' to exit " << endl;
}
}
return userinput;
}
void printVector(vector<int> userinput)
{
int amountofspots = userinput.size();
cout << "Your Vector is ";
for (int i = 0; i < amountofspots; i++)
{
if (i = (amountofspots - 1))
cout << userinput.at(i) << endl;
else
cout << userinput.at(i) << " , ";
}
}
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
for (int i = 0; i < amountofspots; i++)
userinput.pop_back();
for (int i = 0; i < amountofspots; i++)
userinput.push_back(tempvector.at(i));
}
int main()
{
vector<int> CreatedVector = CreateVector();
printVector(CreatedVector);
reverseVector(CreatedVector);
printVector(CreatedVector);
system("pause");
return 0;
}
Change if (i = (amountofspots - 1)) to if (i == (amountofspots - 1)) in the loop in printVector().
Change tempvariable[i] = "-" to tempvariable[i] == '-' in CreateVector().
= is the assignment operator, == is the comparison operator. Also, single characters are surrounded by single quotes, not double quotes.
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
should probably be
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 1; i < amountofspots+1; i++) // Index error
tempvector.push_back(userinput.at(amountofspots - i));
The following:
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
Must become:
for(int i = 0; i < tempvariable.size(); i++)
{
if (tempvariable[i] == '-' || isdigit(tempvariable[i]))
Explanation:
String indices start from 0 and end at size() - 1.
[i] returns a single char. "-" is not a single char but an entire string literal. You cannot directly compare a single char with an entire string. -, however, is a single char, so that comparison will work.
= is not comparison but assignment. == is used for comparison. As your compiler should have warned you!
Note that there are further problems with your code:
if (i = (amountofspots - 1))
You are again mixing assignment and comparison. Make that ==. And pay attention to compiler warnings!
And finally, isdigit is not exactly a great function. In order to really use it correctly, you'd first have to cast the operand to int and at the same time make sure it is not an invalid value, as documented here.
Why don't you just catch the exception thrown by stoi if the specified string cannot be parsed?