C++ beginner, switch isn't outputting first character of string [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
My task is to get a string with no spaces from the user and make the computer count the number of characters, letters, numbers, and special characters (i.e. !##$%^&*) However the program seems to be skipping the first character no matter what category this character falls under. note that it does count it in the number of characters just not in its category
example:
cin >> aZ12!#
output: 6 characters, 1 letter, 2 numbers, 2 special characters.
it always skips the first character.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[100]; // available character string max is 99 characters
int i;
int lett;
int num;
int spec;
cout << "Please enter a continuous string of characters with no spaces" << endl ;
cout << "(example: ASO#23iow$)" << endl << endl ; //shows an example and then adds a blank line
cout << "Enter your string: " ;
cin >> str ;
cout << endl ;
while(str[i] != 0)
{
switch(str[i])
{
case '0' ... '9':
i++ && num++;
break ;
case 'a' ... 'z':
i++ && lett++;
break ;
case 'A' ... 'Z':
i++ && lett++;
break ;
default :
i++ && spec++;
}
}
cout << "your string has " << i << " characters" << endl ;
//prints the number of numbers in the string
cout << "Your string has " << num << " numbers in it." << endl ;
cout << "Your string has " << lett << " letters in it." << endl ;
cout << "Your string has " << spec << " special characters." << endl ;
return 0 ;

In your code, int i is not initialized. Using it is Undefined Behaviour.
int i = 0;
The same goes for the rest of your variables.
Also this doesnt do what you think it does:
i++ && lett++;
This is not do both operations, its a Boolean operator. It employs something called short circuiting, which means if the first part of the && evalutes to false (ie 0), then the expression must be 0 so there is no point in evaluating the rest of it (ie the lett++ part). So for your first loop (i == 0) your lett++ will be short circuited.
Change these to:
i++;
lett++;
If you fix this up it will work:
Live example

Related

enter Odd, Even, zero and negative numbers and count using for and while loop in C++ without using arrray

I've met some problem during programming. I want to write a program to differentiate even numbers, odd numbers, zero values and negative numbers by using while and for loop.
1st question :
However, when I try to run my program, the last number I've entered will not be counted. I know it occur because of my o++ put at the top of the if condition, how should I solve my problem?
2nd question :
For the for loop parts, actually it may ignored those negative values. How should I solve it to let the negative numbers also count in loop ? May I changed the num>0 to num < 100000 to let the for loop works?
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main ()
{
int num ,numbers = 1 ;
char answer = 'Y' ;
int o=0, e=0, z=0 ,n=0 ;
// o for odd numbers, e for even numbers, z for zero values, n for negative numbers
cout << "Enter number" << numbers << ": " << endl ;
cin >> num ;
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
{
if (num % 2 == 0 && num > 0)
{
e++ ;
cout<< "The number of even numbers is :" << e << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num ;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num % 2 == 1 && num > 0)
{
o++;
cout<< "The number of odd numbers is :" << o << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num == 0)
{
z ++;
cout<< "The total of 0 is :" << z << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
}
cout << "The total even numbers is :" << e << endl;
cout << "The total odd numbers is :" << o << endl ;
cout << "The total negative numbers is :" << n << endl ;
cout << "The total zero number is:" << z << endl;
return 0;
}
This line, in main() is really puzzling:
// ...
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
The for(;;) statement is your main loop. The while statement will be executed as long as num is positive.
Let's look at this for() statement in detail:
for (num = num; // num = num ??? this statement does nothing.
num > 0; // the while statement (and the contents of the whule() loop block)
// will only execute if num is > 0.
++num) // if num was > 0 then this loop will run until num overflows...
Removing the for(;;) statement will make your program run a lot better.
Your o++ has nothing do with it.
(Perhaps you have been so convinced about that being the problem that you didn't think of looking elsewhere. It happens to everyone.)
The problem is that your sequence is this:
Check the most recently entered number and print the result
Ask the user for a number, but don't do anything with it
Ask the user whether they want to continue
If they want to continue, repeat from item 1
If they don't, stop counting
And since you stop counting if the user doesn't want to continue, the last number seems to have disappeared.
Fixing it left as an exercise.
(Think more carefully about which order you need to do things in.)
Handling negative numbers requires you to write some code to do that - you handle two cases of positive numbers, and one for zero, but you must have forgotten about the negatives.
Fixing this also left as an exercise.

Getting stuck in infinite loop

When I'm running this program for class, I'm getting stuck in an infinite loop whenever I enter a '|' character to end the while loop. I feel like I'm missing something obvious.
This problem is found on page 126 of Bjarne Stroustrup's C++ Programming book, but as a quick rundown, I'm just supposed to find the largest and smallest numbers that are typed in the by the user and return info on it. Typing in '|' is supposed to exit the loop so that I can get down to the part where it gives information about all the numbers inputted, but whenever I type that character (or any character that's not a number), it creates an infinite loop.
Here is my code.
int main()
{
vector<double> nums;
while (true)
{
double current_num;
cout << "enter a double \n";
cin >> current_num;
if (current_num == '|')
break;
nums.push_back(current_num);
sort(nums.begin(), nums.end());
cout << nums[nums.size()-1] << " is the largest so far.\n";
cout << nums[0] << " is the smallest so far.\n";
}
cout << nums[nums.size()-1] << " is the largest number.\n";
cout << nums[0] << " is the smallest number.\n";
cout << "Number of values entered: " << nums.size() << '\n';
double sum = 0;
for (int k = 0; k<nums.size(); ++k)
sum += nums[0];
cout << "Sum of all values: " << sum << '\n';
for (int j=0; j<nums.size(); ++j)
cout << nums[j] << ' ';
return 0;
}
I was using VS13 in class and I wasn't having this problem, but now I'm coding in notepad++ and using PuTTY to compile at home (although I doubt this has anything to do with it).
You are comparing a character with a double here :
if (current_num == '|')
And this comparison will never do what you want it to do.
Read a character first, compare it with '|', then do a double conversion if necessary.
Note:
For your record the ASCII value of '|' is 124, so if you enter 124 your loop will end...
Because you are trying to insert a non number into a double.
I thing that in your case you should read the input into a string/char and parse it.
you are comparing number with a character.
if (current_num == '|')
current_num contains the number in type double that you are trying to compare with a char which is '|'
Problem is here:
if(current_num == '|'){
}
Instead read in a std::string and parse it to a double.
So the modified snippet will look something like this:
while (true)
{
string strNum;
double current_num;
cout << "enter a double \n";
cin >> strNum;
if (strNum == "|")
break;
istringstream strm(strNum);
strm >> current_num;
nums.push_back(current_num);
sort(nums.begin(), nums.end());
cout << nums[nums.size()-1] << " is the largest so far.\n";
cout << nums[0] << " is the smallest so far.\n";
}

Error when accessing array - stack around the variable 'scores' was corrupted [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
I am new to C++ and have written some code in which I'm getting the following error:
Run-Time Check Failure #2 - Stack around the variable 'scores' was corrupted
What is causing this error?
Here is my code:
#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"
using namespace std;
int getInput();
int main()
{
int scores[5];
int i;
int j;
int numberOfScores;
for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
{
scores[i] = 0;
}
cout << "How many scores do you have to enter?\n" << endl;
cin >> numberOfScores;
for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
{
scores[getInput()] ++;
}
cout << "The number of zeros: " << scores[0] << endl;
cout << "The number of ones: " << scores[1] << endl;
cout << "The number of twos: " << scores[2] << endl;
cout << "The number of threes: " << scores[3] << endl;
cout << "The number of fours: " << scores[4] << endl;
cout << "The number of fives: " << scores[5] << endl;
return 0;
}
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 5.\n";
cin >> enteredScore;
if (enteredScore >= 0 && enteredScore <= 5)
{
return enteredScore;
}
else
{
cout << "Error! The range of scores is 0 to 5.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
return enteredScore;
}
}
It seems that this declaration:
int scores[5];
Is incorrect. This creates an array with 5 numbers in it, indices from scores[0-4], however, you constantly refer to score[5], the sixth element of the array throughout your program. I recommend changing to
int scores[6];
The problem:
You are accessing your array out of bounds in several places.
Here you loop through 6 elements when you only have 5:
for (i = 0; i < 6; i++) // Loops through 6 elements
{
scores[i] = 0;
}
Here you call getInput() and use the return value as the index:
scores[getInput()] ++;
However, the first half of the function accepts inputs from the user in the range 0 to 5, thus allowing access to 6 elements:
if (enteredScore >= 0 && enteredScore <= 5)
It gets even worse if the user enters a number outside that range, as they are then given a second opportunity to enter a number, only this time there is no validation and any number they enter is accepted:
cin >> enteredScore;
return enteredScore;
Finally, you again attempt to access a 6th element here:
cout << "The number of fives: " << scores[5] << endl;
Solution:
First, you need to do one of two things:
Change the for loop, if statement, and cout statements so that they do not access index 5
or:
Create the array so that it has 6 elements: int scores[6];
Secondly, you need to fix the bug in your getInput() function so that it validates the input properly. You could try this for example:
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 4.\n";
cin >> enteredScore;
while (enteredScore < 0 || enteredScore > 4)
{
cout << "Error! The range of scores is 0 to 4.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
}
return enteredScore;
}
You have an error in
cout << "The number of fives: " << scores[5] << endl;
Your array is of size 5 but you are accessing the 6th element.
Same with for (i = 0; i < 6; i++) should be i < 5.

Using characters in a conditional statement in C++

I am trying to write a program which asks for tuition credits and for undergraduate or graduate classes. User enters the number of credits, then must enter U for undergraduate or G for graduate. I am having issues with the conditional statement, if the user enters U, then the price of the undergraduate credits will compute and output, similar with graduate. I am trying to enter U at the IF condition, but either one price or the other outputs.
#include <stdlib.h>
#include <iostream.h>
int main ()
{
const double Under = 380.00 ;
const double Grad = 395.00 ;
char U , G ;
double First, Second, Third, Fourth, Fifth, Sixth ;
cout << endl << endl ;
cout << " To calculate your tuition enter the amount of credits, then enter type of" ;
cout << endl ;
cout << " classes." ;
cout << endl << endl ;
cout << " Enter number of credits. " ;
cin >> First ;
cout << endl << endl ;
cout << " Enter U for Undergraduate or G for Graduate: " ;
cin >> Second ;
cout << endl << endl ;
cout << " Your tuition total is: " ;
Third = First * Under ;
Fourth = First * Grad ;
if ( Second == U )
cout << Third ;
else
cout << Fourth ;
cout << endl << endl ;
system ("Pause");
}
Ok I see a few problems here.
The main one is that characters in C++ have single quotes, like this 'c'. This is most likely the cause of your error. Since you never initialized U anywhere, either do initialize it to 'U' or try
if ( Second == 'U' )
cout << Third ;
Second, though this is not necessarily an error typing cout<<endl<<endl; is a little wasteful as it flushes the buffer for cout twice with only 1 character added in between. typing cout<<'\n'<<endl; would fix that.
You never give a value to U. Right now its content is garbage which is why you get random behavior. Try either assigning 'U' to your variable U or changing the confiditional to:
if( Second == 'U' )
It is more or less all of the already stated:
Remove the declaration of char U since it is never used
Change the type of Second to char (remove from the double list and add char
Second;)
Change the if statement to if ( ( Second == 'U' ) || (
Second == 'u' ) )
I don't see U = 'U' anywhere. You is declared at beginning, but never initialized. You U is just a variable. You have to assign the character 'U' in it.
Second is declared as a double, but it looks like you are expecting the user to enter a character.
use
using namespace std;
under header file

Sudoku game design problems C++

I have (yet another) question about chars. Thanks to those who helped me with this before. I'm trying to do mainly 4 things at this point in the program. That is:
Build a 2D array 9x9 and fill it with underscores.
Ask for a row/column and then the number that the user wishes to go into that row/column as many times as the user wants.
Replace the specified blanks with the specified numbers.
Output the entire 9x9 char array on an ASCII art Sudoku board.
(Solving will come later.)
My problem is that when I enter the row/column and the number that I want to go into that row/column the dash that was originally in that spot disappears, but the number I entered does not appear in its place.
Here is the code so far:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main () {
//Builds 9x9 char array.
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]='_';
}
}
cout << "Input the row #, then the column #, then the number that you wish to fill that spot." << endl;
cout << "Remember that a Sudoku board is 9x9." << endl;
cout << "When you wish to finish input and solve, type all 0's and press enter." << endl;
int rowb;
char row[99];
int columnb;
char column[99];
int numb;
char num[99];
//Inputs the row/column and number to go into specified row/column.
int control=0;
while (rowb!=0){
control++;
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
}
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control];
}
//Builds the Sudoko board and outputs the full 9x9 array.
cout << "╔═══════════╦═══════════╦═══════════╗" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=3; count<6; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=6; count<9; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╚═══════════╩═══════════╩═══════════╝" << endl;
return 0;
}
There is a problem assignment of the number entered in the loop.
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control]; //<<<--- Assignment issue.
}
You are assigning an integer value in a character array & thus when you display you will get the corresponding char for the ascii value & not the integer. Try changing the assignment as follows:
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control] + '0'; // Convert to ascii value of the integer, but will fail if not b/w 0 & 9.
}
Checking if the number entered in is between 1 & 9 is also advised if you choose to use the above observation.
Please add checks for the row & column entered as enter values which are not b/w 1 & 9 will lead to undefined behaviour due to accessing out of bound array elements if the values entered are not b/w 1 & 9.
Also as mentioned by Benjamin Lindley please update strlen code.
Hope this helps!
length=strlen(row);
This is undefined behavior, because row[0] was never initialized, and you never null terminate the string.
char row[99];
...
int control=0;
while (rowb!=0){
control++;
...
row[control]=rowb-1;
...
Notice that the first time through the loop, control is 1. So, you're setting the value of row[1], but not row[0]. Move the increment to the end of the loop. There may be some other problems, but this is the primary one responsible for the behavior you're seeing.
Also, for strlen to work, you need to null terminate the string.
And finally, you're making the same mistake you've made in this question and this question. Why aren't you seeming to get that? Chars display differently than ints. The following code will not display the number 1:
char c = 1;
std::cout << c;
Look at the answers to those other two questions.