C++ Beginner - While loop repeating first iteration [closed] - c++

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
All,
So I've been really racking my brain about this one. I have a section of my program that needs to count spaces/vowels/characters in a user-specified string. This is one of those "teach you the way no one would do it because you can only used what we've covered in class already" kinds of assignments. So I have the user input a text, ending with a sentinel char, which in this case is '#'. The loop works wonderfully in regards to exiting when the sentinel is encountered, but it keeps iterating twice over string[0]. Here's the code:
i = 0;
characterToBeProcessed = userInputText.at(i);
while (characterToBeProcessed != LOOP_SENTINEL)
{
fout << characterToBeProcessed;
// Convert to lowercase
characterToBeProcessed =
static_cast<char> (tolower(characterToBeProcessed));
// Increment character counters
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
totalCharacterCount++;
break;
case ' ':
totalSpaceCount++;
totalCharacterCount++;
break;
default:
totalCharacterCount++;
break;
}
characterToBeProcessed = userInputText.at(i++);
}
So when I input at the prompt:
"Please input a text to be analyzed, ending with the # character: "
Hi there, my friend!#
The output is:
Below is the text entered by the user:
HHi there, my friend!
Total characters: 21
Total vowels: 5
Total blank spaces: 3
I've had the program output the chars for .at(0) and .at(1), and those give me the correct characters, I just can't figure out why the loop iterates twice for the first char and then works fine after that second time through. The counts/output are otherwise correct except for the first char being duplicated. Any appreciation would be greatly appreciated.

As others have said, the right way to solve problems of this kind is to use a debugger. It would save you lots and lots of time.
But in any case, your error is that at the end of your while loop, you do this:
characterToBeProcessed = userInputText.at(i++);
But before your while loop, you do this:
characterToBeProcessed = userInputText.at(i);
Your problem is that you are not incrementing i each time you use it, which naturally results in the observed behavior.

A character at the first position is read twice
i = 0;
characterToBeProcessed = userInputText.at(i);
^^^^^^
while (characterToBeProcessed != LOOP_SENTINEL)
{
//...
characterToBeProcessed = userInputText.at(i++);
^^^^^^^^
}
If you need to use the while loop then it can look like
i = 0;
while ( ( characterToBeProcessed = userInputText.at( i++) ) != LOOP_SENTINEL )
{
//...
// remove the next statement
// characterToBeProcessed = userInputText.at(i++);
}
Also this statement
totalCharacterCount++;
is used under each label. It is better to place it outside the switch statement either before it or after it. For example
totalCharacterCount++;
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
break;
case ' ':
totalSpaceCount++;
break;
default:
break;
}

Related

why am i getting time limit exceed

I was trying to solve this problem in leetcode.
problem: heap problem
this is my code:
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
priority_queue<pair<int,int>,vector<pair<int,int>>>mxheap;
for(int i=0; i<score.size(); i++){
mxheap.push({score[i],i});
}
vector<string>ans(score.size());
int place = 1;
while(!mxheap.empty()){
switch(place){
case 1:
ans[mxheap.top().second] = "Gold Medal";
mxheap.pop();
break;
case 2:
ans[mxheap.top().second] = "Silver Medal";
mxheap.pop();
break;
case 3:
ans[mxheap.top().second] = "Bronze Medal";
mxheap.pop();
break;
default:
ans[mxheap.top().second] = to_string(place);
}
place++;
}
return ans;
}
};
I don't know why I am getting the time limit exceeds I also tried removing the pair and using a map but that also didn't work.
I also saw some answers in discuss section those answers were also of (nlogn) time complexity but they worked fine mine is also (nlogn) still its not working can someone please tell me what am I doing wrong here.
Because you are not popping off the element in the default case.
ans[mxheap.top().second] = to_string(place);
mxheap.pop(); // Add this
which leads to an infinite while loop since your queue never becomes empty and hence the TLE.
You should be using a debugger to root-cause these problems and add breakpoints in your program to verify the expected program state at those points.

C++ Switch Cases

I was doing a quiz online based on the C++ switch statement. I came across a question and I have a fair understanding of how switch statements work but this one question made absolutely no sense to me. Can someone please explain?
Why is the answer D and not C?
Is Case 2: the default case or what?
This quiz can be found at: http://www.cprogramming.com/tutorial/quiz/quiz5.html
Here's how this code behaves.
x is equal to zero
so cout<<"Zero"; is executed.
Since there's no break; after it,
the second case is executed: cout<<"Hello World";
And since cout<<"something"; doesn't add a newline after printing, they're printed as a single word.
since there is no break; statements in each case, the code will fall-through from case 0: to case 2:.
In C++ a case will "fall-through" if there is no break statement:
int temperature = 20;
switch(temperature)
{
case 20:
cout << "it's nice and warm";
case 25:
cout << "it's a bit hot";
break;
case 30:
cout << "It's way too hot!";
break;
}
This will print out:
it's nice and warm AND it's a bit hot because there is no break statement.
Since, x=0. It matches the 2nd case i.e. (case 0: cout << "Zero"; ). But there is no break statement to break out of the switch statement, it executes next cases too. If you have other cases its gonna execute and stop only when it find break statement or reaches the end of the switch case.

Using a switch in a do..while loop, in C++

A simple programm that reads strings, and responds using a switch;
in this do-while loop containing a switch, I am able to run case 1-4 with no issues, but once i hit the default case, the programme simply loops the default case over and over again the code is as follows;
do { switch ( switchstring (entry, input) )
/*the switchstring function is one 1 wrote to convert a given entry(string),
into an input(integer)*/
{
case 1:
//code
repeat = 2;
break;
case 2:
//code
repeat = 2;
break;
case 3:
//code
repeat = 2;
break;
case 4:
//code
repeat = 2;
break;
default:
//code
repeat = 1;
break;}} while(repeat == 1);
the 2nd question is regarding my switchstring() function; is there a way to change the switch function such that it reads;
case (insert string):
i.e. so that I can remove the entire switchstring() function
thanks in advance!
Show us how switchstring (entry, input) works.
The problem you are facing is because, in default you do the following:
repeat = 1;
Which makes while(repeat == 1) always true. And then switchstring (entry, input) always return something that makes your switch block always go the the default case again.
When no case will be true in switch, then it will go in default case of switch and you are specifying repeat=1; in default. After that while condition will be checked and it will be true because repeat is 1, again it will go to do and check condition, your switch function will return something and it will go to default.
To solve 2nd question regarding your switchstring() function, you have to show your code what you are doing in that function, So that i can give you best suggestion.

How can I give the option of repeating the input for a switch statement in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi I'm playing around with basic looping techniques and I'm trying to make the following code work. When the user inputs a number other than those allowed it will go to the default where I want to give them the option to try again (without just subbing the whole code into the default) or to just exit.
#include <iostream>
using namespace std;
int main(){
int input;
char ans;
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
break;
}else{
continue;
}
}
}
When I run this I get the error that continue isn't in any loop. I'm not really quite sure how to use the continue statement. Any help with this would be greatly appreciated.
Put your switch statement inside a loop (while(1)) or (for(;;)), then it will work.
From http://en.cppreference.com/w/cpp/language/continue:
continue statement:
Causes the remaining portion of the enclosing for, range-for, while or do-while loop body skipped.
Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.
You need to put the core of your function in a for loop or while loop.
bool stop = false;
while ( !stop )
{
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
stop = true;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
stop = false;
}
}
}

Using getchar() function

I used getchar() to stop the while string. My problem is that it does stop the while string if I type one or two characters, if the user input is more the two characters nothing happens.
here is the code:
printf("enter srting\n");
while ((tmp=getchar()) !='\n') { \\here is my problem
count_letters++;
/* COUNTING WORD THAT START WITH LETTES L,A,C,H */
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
} /* end of count letters while */
n1=n2;
n2=n3;
n3=tmp;
if (n1=='H' && n2=='Y' && n3=='A') {
count_hya++;
}
} /* end of getchar while */
printf("\n");
printf("%d", count_letters);
I believe it's your code :
"while (count_letters%3==0))"
is something wrong!
because when you type more than three letters,your variable "count_letters" will add to 3 due to the code:"count_letters++;".
May be you could change the "while" to "if" and see if it's working correctly~
Here's the problem:
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
}
when your the third character is read, your program enters a infinite loop because of (count_letters%3==0)
I can't understand the purpose of your code.
I suggest using gets() and string manipulation functions because you are processing an entire line. (see string.h)
getchar() is also less efficient compared with gets() + for-loop