how can i make the loop and change number to string - c++

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int number=0;
cout<<"enter an number to cumpute";
cin>>number;
if(number=0)
cout<<"0"<<endl;
for(number>0;51>number;) {
number--;
cout<<"=";
}
for(number>10;number%10==0;) {
cout<<"|";
}
for(number>5;number%5==0;) {
cout<<"+";
}
cout<<endl;
system("PAUSE");
return 0;
}
(i got textbook called by Y.Daniel Liang. I can not find any thing like this) I have no idea how to make this loop work and I try use "while" and not working either. Should i just cout the "=" "+" "|", or start as string. I hope the output look like this.
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 6
| ====+> 6
| Enter Number: 12
| ====+====|=> 12
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 53
| ERROR: 53 is not in acceptable range.
| Enter Number: 33
| ====+====|====+====|====+====|==> 33
| Enter Number: 0
| 0
| Enter Number: 5
| ====> 5
| Enter Number: -1
------------------------------------------------
BarPlot – End Plot by User Request

There is no need for you to convert a number to a string in order to solve the problem. The object cout can handle printing both numbers and strings without you needing to cast between them.
//example
int number = 1;
string str = "hello;
char c = '!';
//print hello1!
cout << str << number << c;
Here is a solution to the problem that does not require the need to cast an integer to a string.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//output inital prompt
cout << "BarPlot – A Simple Bar Graph Plotter:\n";
cout << "Input a number in range [0 50] or a negative number to terminate.\n\n";
//read in input
int number = 0;
cout << "Enter Number: ";
cin >> number;
//continue asking for input until a negative number is given
while (number >= 0){
for (int i = 1; i < number; ++i){
//special symbol every 10th char
if (i % 10 == 0) cout << "|";
//special symbol every 5th char
else if (i % 5 == 0) cout << "+";
//every other char
else cout << "=";
}
//print 0 or the number with an arrow before it
if (number == 0) cout << 0;
else cout << "> " << number << "\n";
//re-ask for input
cout << "\nEnter Number: ";
cin >> number;
}
//output ending message
cout << "BarPlot – End Plot by User Request\n";
return EXIT_SUCCESS;
}

Related

How to limit cin to integers within the int data range?

I am wondering how to only allow inputs for a cin which are within the int data range.
// This program counts the number of digits in an integer
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, k;
cout << setw(20) << "Value Entered" << setw(20) << "Number of Digits" << endl;
while(1==1)
{
k = 1;
cout << setw(10) << "";
cin >> i;
while(i > 2147483647 || i < -2147483648)
{
cout << setw(10) << "";
cin >> i;
}
while( i / 10 > 0)
{
i = i / 10;
k++;
}
cout << setw(30) << k << endl;
}
return 0;
}
With the method I have it just gets stuck in the loop repeating 1.
EDIT:
Sample Output Format (Required)
"Value Entered" "Number of Digits"
14 2
225 3
-1000 4
Sample Output (What I have)
Value Entered Number of Digits
45
2
456
3
258
3
-2546
4
The extraction will fail if the number falls outside of the range for the type that it's being read into. When this happens the state of the stream will be set to failure, so you simply need to check for this state, and then reset the stream to a valid state:
while (!(cin >> i)) {
cin.clear();
cin.ignore(numeric_limit<streamsize>::max(), '\n');
}
clear() clears the error flags and ignore() puts the stream on a new line so that new data can be read. You may need to include <limits> for the code to work.
The condition for your second loop should be while (i > 0). As you had it you were off by one digit.

cin a char into an int variable to stop a loop

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;
}
}

Print last digits of an integer gradually?

I am trying to to print the last digits of a user inputted integer.
For example if the user inputs 5432
my output is
2
32
432
5432.
I have managed to write the code for this using a while loop, however i don't understand why my loop does not terminate, please help me terminate it?
void main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input % modulu; // test checks if all the number has been printed
//disect number
while (test > 0);
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = input % modulu;
}
}
test is always > 0 for any input > 0
you can achieve the same with different loop:
int input, modulu = 1;
cout << "Please enter a number: ";
cin >> input;
do {
modulu *= 10;
cout << endl << (input % modulu) << endl;
} while ((input % modulu) != input);
Just
test = input / modulu;
instead of test = input % modulu;
For starters there is a semicolon after the while statement.
while (test > 0);
^^^
So the loop is infinite provided that the last digit of the entered number is not equal to 0.
However if you remove the semicolon the condition is invalid because test == 0 only in the case when the last digit is equal to 0.
Take into acount that main in C++ shall have return type int.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
const unsigned int Base = 10;
std::cout << "Please enter a non-negative number (0-exit): ";
unsigned int x;
if ( !( std::cin >> x ) || x == 0 ) break;
unsigned int y = x;
unsigned int modulo = 1;
do
{
modulo *= Base;
std::cout << x % modulo << std::endl;
} while ( y /= Base );
std::cout << std::endl;
}
}
If for example to enter
123456789
0
then the output will look like
Please enter a non-negative number (0-exit): 123456789
9
89
789
6789
56789
456789
3456789
23456789
123456789
Please enter a non-negative number (0-exit): 0
Your first problem is here:
while (test > 0);
The ; terminates the while-statement and the code will stay in the while forever. In other words - all the code below is never executed. Remove the ;
Your second problem is the way you handle test - don't take modulo but divide by 10 instead. Like this:
int main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input; // <------------- Just make test equal to the input
while (test > 0) // <------------- The ; removed
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = test / 10; // <----------- Divide by 10
}
return 0;
}
Notice that the above code has some problems with zeros, e.g. 1001 will output 1 1 1 1001 instead of 1 01 001 1001.
You can fix that by a completely different approach using stringinstead of int
Like:
int main()
{
//declare variables
string input;
//read input from user
cout << "Please enter a number: ";
cin >> input;
cout << input << endl;
int size = input.size();
int tmp = size;
while (tmp >= 0)
{
for (int t = tmp; t < size; t ++) cout << input[t];
cout << endl;
--tmp;
}
return 0;
}

Unique String printing every 5th 10th and last position

Been stumped for a good day now on this one, I know I just need the "=" sign and ">" end piece to the question.Any hints or advice>?
int main()
{
//Calling in Variables
int data;
int counter;
//Step 1:Prompt the user to pass in a positive integer between (0-50)
cout << "Type in a number between 0-50 to plot your bar: " << endl;
cin >> data;
//Step 2: Error check for bad numbers that have been input.
if(data < 0) {
cout<< "ERROR: " << data << " is not in acceptable range."<< endl;
}
//Step 3:
if(data >= 0 && data <= 50){
for(int counter =1; counter <= data; counter++) {
if(counter % 10 !=0)
cout<< "|";
else(data%5 == 0)
cout << "+";
}
}
else
cout << "BarPlot - End Plot by User Request"
return (0);
}
Create a simple Bar Graph Plotter (BarPlot) that takes in a positive integer number between [0 50], and plots the
number as a simple bar. The program should only accept data within this range. Any negative value input should
terminate the Program. Any input larger than 50 should result in an error message and a prompt to enter another
number.
Example Output:
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 8
| ====+==> 8
| Enter Number: 15
| ====+====|====> 15
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 65
| ERROR: 65 is not in acceptable range.
| Enter Number: 0
| 0
| Enter Number: 1
| > 1
| Enter Number: 5
| ====> 50
| Enter Number: -1
BarPlot – End Plot by User Request
You have a really simple question that you have made complex by putting it in a big lump of text. You have pretty simple logic, you want to print out = except for every 5th and 10th number. You were basiclly already there:
for(int counter =1; counter <= data; counter++) {
if(counter % 10 ==0)
cout<< "|";
else if(counter%5 == 0)
cout << "+";
else
cout << "=";
}
cout << ">" << yournumberthing << endl;
You just needed to think about it some more.

Counting digits in a number without using strings

i have the next code which asks the user for a really long number like 100000000 and then it prints how many times a given digit appears on that number, the code works fine and does everything correctly, but the professor told me that i dont have to use strings or chars, but when the code asks the user for a number it necessarily needs a string and i don´t know how to modify it, i used the gmp library
#include <iostream>
#include <stdio.h>
#include <gmp.h>
#define MAX 40
using namespace std;
void searchDigit(FILE *fd);
int NewNumber();
int main()
{
FILE *fd;
int otherNumber;
string text;
mpz_t num;
do
{
if((fd = fopen("File.txt","w+"))!= NULL)
{
mpz_init(num);
cout << "Give me the number: " << endl;
cin >> text;
mpz_set_str(num,text.c_str(),10);
mpz_out_str(fd,10,num);
fclose(fd);
searchDigit(fd);
otherNumber = NewNumber();
}
else
cout << "Fail!!" << endl;
}while(otherNumber);
return 0;
}
void searchDigit(FILE *fd)
{
int car,continue = 1,r;
char answer,digit;
if((fd = fopen("File.txt","r"))!= NULL)
{
do
{
r = 0;
fseek(fd,0,SEEK_SET);
cout << "What digit do you want to search? " << endl;
cin >> digit;
while((car = fgetc(fd))!= EOF)
{
if(car == digit)
r++;
}
cout << "The digit x=" <<digit<< " appears " << r << " times" << endl;
cout << "Do you want to search any other digit? " << endl;
cin >> answer;
if(answer != 'S')
continue = 0;
}while(continue);
}
else
cout << "Fail!!" << endl;
}
int NewNumber()
{
char answer;
cout << "DO you wish to work with a new number? " << endl;
cin >> answer;
if(answer == 'S' || answer == 's')
return 1;
else
return 0;
}
Thanks in advance
Depends on how big your input might actually be... but for retrieving digits you could do something like:
#include <iostream>
using namespace std;
typedef unsigned long long UINT64;
int main() {
UINT64 i;
std::cin >> i;
while (i >= 1) {
int digit = i % 10;
std::cout << digit << " ";
i /= 10;
}
}
input: 18446744073709551614
outputs: 4 1 6 1 5 5 9 0 7 3 7 0 4 4 7 6 4 4 8 1