Please disregard some of the undeclared variables. I do not really know what is wrong.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
while (number > 0){
ans = number / 10;
++count;
if (ans == 0){
cout << "The number has " << count << "digits";
break;
}
}
return 0;
}
You're never actually changing number, so every iteration, you set ans to the same thing and run the same test.
As indicated by others, you are not updating the loop variable (number) anywhere inside the loop. Hence it is very likely to get in an infinite loop. Here is a sample updated code you can try out.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
if (number<=0){
cout << "Incorrect input.";
}
else{
while (number>0){
number = number / 10;
count ++;
}
cout << "The number has " << count << " digits";
}
return 0;
}
Related
I am trying to implement random_function(), which outputs the amount of random numbers within a range (user input), and count_function() to count for the value that the user wants to look up in the outputted random numbers. I made the random numbers to be saved in an array called randomlist[] so that it can be used to count for the value from the outputted random numbers. However, I cannot declare an array without its fixed size in the header file and define its size in the count_function.cpp. So I cannot use randomlist[] in the count_function() without redefining it (which is meaningless...).
Is there a way to declare array without defining its size, in the header file?
Here is the source code:
header file:
#pragma once
using namespace std;
class Rand
{
public:
// Rand();
int range,min,max;
char key;
void Random_function();
void Count_function();
// randomlist[]; something like this, which that is not possible in c++
};
This is randomfunction.cpp:
#include <iostream>
#include "random_function.hpp"
using namespace std;
void Rand::Random_function()
{
beginning:
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0 || cin.fail())
{
cout <<"Error! Please enter valid number and try again! "<<endl;
goto beginning;
}
else
{
reenter:
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
srand((unsigned)time(NULL));
if(max<min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
goto reenter;
}
else
{
int randomlist[range]; //I defined the size of the randomlist here but I want to use this outside of the random_fucntion() as well.
for(int i=0 ; i < range; i++)
{
randomlist[i] = min + (rand() % static_cast<int>(max - min + 1));
cout <<i+1<<". "<< randomlist[i] <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
cout <<"Do you want to continue? y/n"<<endl;
cin >> key;
if(key=='y')
{
Count_function();
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
else
{
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
}
}
void Rand::Count_function()
{
int n,count=0;
reenter2:
cout<<"Enter the value to count for: ";
cin>>n;
if(cin.fail())
{
cout<<"Please enter valid value to count for"<<endl;
goto reenter2;
}
else
{
for(int i=0 ; i <range; i++)
{
if(randomlist[i]==n)
{
count++;
}
}
}
cout <<"The number of '"<<n<<"'s in the given list is: "<< count <<endl;
}
main:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int main()
{
Rand call;
call.Random_function();
}
When you want to use an array, but the size cannot be known at compile-time, the generally accepted approach in C++ is to use a std::vector.
I would like to read numbers into a static array of fixed size 10, but the user can break the loop by entering character E.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] != 'E')
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
However, I get the following results while entering E:
Enter upto 10 integers. Enter E to end
Enter num 1:5
5
Enter num 2:45
45
Enter num 3:25
25
Enter num 4:2
2
Enter num 5:E
-858993460
Enter num 6:-858993460
Enter num 7:-858993460
Enter num 8:-858993460
Enter num 9:-858993460
Enter num 10:-858993460
10
Press any key to continue . . .
How can I fix this code in the simplest way?
cin fails for parsing character 'E' to int. The solution would be to read string from user check if it is not "E" (it is a string not a single char so you need to use double quotes) and then try to convert string to int. However, this conversion can throw exception (see below).
Easiest solution:
#include <iostream>
#include <cmath>
#include <string> //for std::stoi function
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
std::string input;
cin >> input;
if (input != "E")
{
try
{
// convert string to int this can throw see link below
myArray[i] = std::stoi(input);
}
catch (const std::exception& e)
{
std::cout << "This is not int" << std::endl;
}
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
See documentation for std::stoi. It can throw exception so your program will end suddenly (by termination) that is why there is try and catch blocks around it. You will need to handle the case when user puts some garbage values in your string.
Just use:
char myArray[10];
because at the time of taking input console when get character then try to convert char to int which is not possible and store default value in std::cin i.e. 'E' to 0 (default value of int).
Use below code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] == 'E')
{
break;
}
else
{
cout << myArray[i] << endl;
count++;
}
}
exitloop:
cout << count << endl;
system("PAUSE");
return 0;
}
Output:
Enter upto 10 integers. Enter E to end
Enter num 1:1
1
Enter num 2:E
1
sh: 1: PAUSE: not found
If you debug this, you will find all your myArray[i] are -858993460 (=0x CCCC CCCC), which is a value for the uninitialized variables in the stack.
When you put a E to an int variable myArray[i]. std::cin will set the state flag badbit to 1.
Then when you run cin >> myArray[i], it will skip it. In other words, do nothing.
Finally, you will get the result as above.
The problem is that attempting to read E as an int fails, and puts the stream in an error state where it stops reading (which you don't notice because it just doesn't do anything after that) and leaves your array elements uninitialized.
The simplest possible way is to break on any failure to read an integer:
for(int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
if (cin >> myArray[i])
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
If you want to check for E specifically, you need to read a string first, and then convert that to an int if it's not E.
As a bonus, you need to handle everything that's neither int nor E, which complicates the code a bit.
Something like this:
int count = 0;
string input;
while (cin >> input && count < 10)
{
if (input == "E")
{
break;
}
istringstream is(input);
if (is >> myArray[count])
{
cout << myArray[count] << endl;
count++;
}
else
{
cout << "Please input an integer, or E to exit." << endl;
}
}
I was writing a code that calculates the two factors of any given number using two nested 'While' loops but after just one iteration the loop just stops
Program
#include <iostream>
#include <conio.h>
using namespace std;
long int Password;
void main()
{
long int n=2,n1=2;
cout<<"Type the number whose factor you need"<<endl;
cin>>Password;
while( n < 3600 )
{
while( n1 < 3600 )
{
if( n*n1 == Password )
{
cout<<"your Factors are "<<n<<" and "<<n1<<endl;
getch();
}
else
{
n1++;
break;
}
}
n++;
}
}
Output is only working for small numbers but when a little big numbers are inserted the program terminates. I am not understanding the problem as the code is perfectly fine. Am I having a less powerful processor?
Your program is not calculating the factors of any given number. Also, naming the number "Password" is confusing.
Maybe you want something like this in C++:
#include <iostream>
using namespace std;
int main() {
unsigned int number;
cout << "Enter a positive integer whose factors you need: " << endl;
cin >> number;
cout << "Factors of " << number << " are ";
for (int i = 1; i <= number; ++i) {
if (number % i == 0)
cout << i << " ";
}
cout << endl;
return 0;
}
As was noted in the comments, in C++ you have int main() not void main(), even though some compilers do support void main().
I tried to implement the do..while loop in a simple program. In the program, I ask for a payroll amount, then calculate the sum of the payroll and outputs the sum and the number of valid entries. That's too simple so I decided to add some error checking.
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
const int SENTINEL = -1;
int main(){
int payroll, payroll_sum, counter = 0;
do{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
}while(payroll != SENTINEL);
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
The code works, but it bugs me that I have to deduct one from the counter and add one to the sum because I don't know how to make the program ignore the SENTINEL input. And, I'm sure that there's a better way to do the error handling. Thanks in advance.
This is how I would have written it as it's quite a bit cleaner. A few things I noticed that you may want to take note of:
It's good practice to initiate variables when you declare them.
Read up about continue and break in loops as well as when to use a do-while or a while loop.
Happy coding!
const int SENTINEL = -1;
int main() {
int payroll_sum = 0;
int payroll = 0;
int counter = 0;
while (payroll != SENTINEL) {
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL) break;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
continue;
}
else {
payroll_sum += payroll;
counter++;
}
}
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
Use
continue;
Instead of
int main(payroll);
And also, initialize payroll_sum by using
payroll_sum=0
Before the loop. Also, remove
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
And change the last two couts to
cout << "\n\nTotal payroll amount is: " << payroll_sum+1;
cout << "\nTotal number of entries is: " << counter-1;
Seems like a simple question about condition logic. There are plenty of different ways to structure your if conditions but one way that would be more efficient than your current code could be:
while(true)
{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL)
break;
if((payroll < SENTINEL))
{
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else
{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
}
If you don't like using while(true) I can provide another example. Cheers
I am having a problem with this code. Although it should say that this number is not prime, as i put a ridiculously large number that i know to be nonprime (252345435465, or even 1000000000000 as an example), it states that the number is prime.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
Is there something I'm doing wrong?
The values you are putting in are too big for an int to hold. They are overflowing the 32 bit limit of a signed int (-2147483648 through 2147483647).
First, to avoid including the non-standard header <stdafx.h>, just turn off precompiled headers in your Visual C++ project (right click the project, then properties).
The main problem is that you're inputting values too large for the int type.
To detect that, simply check the state of the stream after the input operation:
#include <iostream>
#include <stdlib.h> // EXIT_FAILURE
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
if( cin.fail() )
{
cout << "Sorry, that's not a valid `int` number." << endl;
return EXIT_FAILURE;
}
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
A 32-bit signed int can take a range of values between –2,147,483,648 to 2,147,483,647. Your number is too large for that range.
Either use a more suitable variable type, or only input numbers which are within range for the variable you are using.
See this answer for more information on C++ data types and their ranges.