Input an integer, get spaced output in C++? - c++

I'm working on homework and I'm stumped on this problem: Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, [...], output 4000 as
4 0 0 0, and the individual digits of -2345 as 2 3 4 5.
Here's my code so far:
int main()
{
string a; //declares string
cout << "Type an integer: "; //prompts user to input an integer
cin >> a; //stores into string a
cout << "There are " << a.size() << " digits in " << a << endl; //retrieves length of string a
cout << a.at(0);
cout << endl;
system ("pause"); //pauses the system so user can read the screen
return 0; //returns 0 if program works properly
}
Can anyone enlighten me on what I'm doing wrong/what my next step is?

So the steps are..
store the input
display them all one by one separated by spaces
figure out the sum and display that
.
#include<string>
#include<iostream>
using namespace std;
int main()
{
string a;
cout << "Type an integer: ";
// 1. store the input
cin >> a;
// 2. display them all one by one separated by spaces
for(int i=0;i<a.size();++i)
cout << a[i] << ' ';
cout << endl;
// 3. figure out the sum and display that
int total = 0;
for(int i=0;i<a.size();++i)
total += a[i] - '0';
cout << total << endl;
system("pause");
return 0;
}
The tricky part is getting the correct sum in step 3.
total += a[i] - '0';
Lets say for example that a[i] is the character '4'. The ASCII value of character '4' is the integer equivalent of 52, and the ASCII integer equivalent of '0' is 48. Therefore if we take '4' - '0', we will get the difference of 4, which is the integer representation we are looking for in this case.
Here is a simple ASCII chart with character values.
Hope this helps!

You probably want to input the number as a string. This will allow you to do digit by digit processing. Then the user will enter the number once instead of many times as digits.

You could try this piece of code:
int num = 0;
cin>>num;
//Make sure array is large enough to hold all digits
//For an int 10 digits it the max
int digits[10] = {0};
//This variable tracks the count of actual number of
//digits extracted from user input
int digitCount = 0;
while (num > 0)
{
digits[digitCount] = num % 10; //Extract digit at units place
num = num / 10; //Advance through the number
digitCount++;
}
for(int count= digitCount-1 ; count >= 0; count-- )
{
cout<<digits[count]<<" ";
}
Note that the printing loop runs backwards (i.e from digitCount to zero) because the digits are extracted and stored starting from the units place. For a number a like 12345 the digits array will contain 5 4 3 2 1.

Rhonda, I can understand your frustration, computers are like that... they do what you say, not what you mean :-) Hang in there.
You say your program should output each of the digits in the number, yet your program asks the user to enter each of the digits. That is confusing.
Also, you first assign a value to "num" here
cin >> num;
then you overwrite "num" in this line
cin >> num >> a;
I'm not sure what you mean to do here, but what you're telling the computer to do is to read an integer from the input and assign it to "num" and assign the rest to the line to string "a"... if the rest of the line just has a space, the space will be discarded... it acts as a separator. That is probably confusing you as well.

int main()
{
int runningTotal = 0;
std::string inputString;
std::cin >> inputString;
for ( std::string::iterator _it = inputString.begin();
_it != inputString.end(); ++_it )
{
// *_it now represents an individual char of the input string
char a = *_it; char* b = &a;
if ( a != '-' )
{
runningTotal += atoi( std::string( b ).c_str() );
std::cout << *_it << " ";
}
}
std::cout << std::endl << "Total of all digits: " << runningTotal << std::endl;
std::cin.get();
std::system( "pause" );
return 0;
}
I threw this together quickly for you. Hope it's of help.

Related

C++ isdigit() Query for converting a char array to an int array

I am trying to convert an input character array, to an int array in c++.
Inputs would be in a format like: 'M 911843 6', where the first value of the char array is a uppercase letter, which I convert to an ASCII value and -55.
Edit: I should also mention I just want to use the iostream library
The last value of the char array can be a letter or number also.
I want to retain the exact number value of any input in the char array, which is why I convert to an ASCII value and -48, which retains the same number, but stored as an int value:
I use the checkdigit() function to check if the char input is a number or not.
The difficulty I am facing is that the input will always have a blank space at i[1] and i[8] (if we count i[0] as the first value) - so I try to give them an int value of 0 (int of a " " is 0)
Upon several debugging attempts, I found that it is after the blank space is given a 0 value, the output in my for loop keeps outputting the wrong values, I suspect it has something to do with the isdigit() function in my for loop.
If the spaces from M 911843 6 were removed, the int output is usually fine, e.g. a char input of
M9118436 will return an int array of [22][9][1][1][8][4][3][6].
The output with spaces: [22][0][-183][-120][37][-118][-59][72][0][-55]
Ideal output: [22][0][9][1][1][8][4][3][0][6]
The code is listed below, any help or advice would be greatly appreciated, thanks!!
#include <iostream>
using namespace std;
int main() {
char a[10];
int z[10];
int i = 0;
int r; //result of the isdigit check (0 or 1)
cout << "in ";
cin >> a;
for (int i = 0; i < 10; i++) {
r = isdigit(a[i]);
if (r == 0) {
if (i==1 || i==8)
z[i] = 0;
else z[i] = int(a[i]) - 55;
}
else {
z[i] = int(a[i]) - 48;
}
}
cout << z[0] << "\n" << z[1] << "\n"<< z[2]<< "\n" << z[3] << "\n"<< z[4] << "\n"<< z[5] << "\n"<< z[6] << "\n"<< z[7]<< "\n" << z[8] << "\n"<< z[9];
return 0;
}
The problem is that cin >> a; does not read sizeof(a) characters, but up to the first space character and will terminate that with a null.
That means that you array will containt 'M', '\0' and 8 uninitialized characters. You must read the characters one at a time with unformatted reads:
for (auto& c : a) {
cin.get(c);
if (!cin) {
cerr << "Incorrect input\n";
return EXIT_FAILURE;
}
}
Just a follow on from Serge's answer which gave me a good understanding of how strings are read - I solved my problem using cin.getline() function.

Adding string characters to a for loop after converting int to string in c++

So I'm busy with a school project and new to C++ and I'm a bit stuck, so here is the question:
When your program begins, it should prompt the user to enter an integer number greater than or equal to 1. This number should be assigned to a variable called control.
You must create a for loop that iterates a number of times equal to control. Each time it iterates, it must append a numeric digit to a string, with the first digit added being 1, and for each iteration, the next number is the previous number multiplied by the original number input. Additionally, the spaces that would ordinarily be between the numbers must instead be the ”#” symbol.
Once the loop is finished iterating, it must display the string that you have constructed.
As a hint, consider the use of string streams for converting between integer to string.
Examples of this program are below:
Please enter a number: 3
1#3#9
Please enter a number: 5
1#5#25#125#625
Please enter a number: 1
1
And here is my code so far :
int main()
{
int control;
int value;
string final;
int test;
stringstream convert;
cout << "Please enter a number: " << endl;
cin >> control;
if (control >= 1)
{
value = 1;
for (int count = 2; count <= control; count++)
{
value = value * control; <---- SO IM STUCK HERE
convert << value; TRYING TO INSERT "#"
final = convert.str() + "#"; BETWEEN THE VALUES
}
cout << "1#" << final << endl;
}
else
{
cout << "Please enter a valid number!" << endl;
}
system("pause");
return 0;
}
Thanks in advance for the help.
Okay so it seemed to be a very simple fix, I feel like an idiot but thanks for the help.
Old code : convert << value;
New code : convert << '#' << value;

Stack around the variable is corrupted

I have what seems like a pretty simple, beginner question that I must be missing something obvious. I am just trying to prompt the user to input a 4 digit number and then take in the input as an array, splitting up the digits to be by themselves. I thought it hade something to do with "cin >> input[4]" I just can't seem to get the right answer.
int main()
{
int input[4]; //number entered by user
cout << "Please enter a combination to try for, or 0 for a random value: " << endl;
cin >> input[4];
}
When I go to run it, I get an error message "Stack around the variable was corrupted.
I tried looking at similar examples in other questions but I just can't seem to get it right. I need the input as one 4 digit number and then split it up to a 4 position array.
If anyone could help I would greatly appreciate it.
Your array is of size 4, so elements have indicies 0 .. 3; input[4] is located behind the end of your array so you are attemping to modify memory not allocated or allocated for other stuff.
This will work for you:
cin >> input[0];
cin >> input[1];
cin >> input[2];
cin >> input[3];
You do not need an arry to input 4 digit number.
int in;
int input[4];
cin >> in;
if(in>9999 || in < 1000) {
out << "specify 4 digit number" << endl;
return;
}
input[0] = in%1000;
input[1] = (in-1000*input[0])%100;
input[2] = (in-1000*input[0]-100*input[1])%10;
input[3] = in-1000*input[0]-100*input[1]-input[2]*10;
The problem is that you are trying to read in a character that does not exist (the one at index 4).If you declare input as int input[4];, then it doesn't have any characters at index 4; only indices 0...3 are valid.
Perhaps you should just use an std::string and std::getline(), and you could then parse the user input to integers however you like. Or you can try
std::cin >> input[0] >> input[1] >> input[2] >> input[3];
if you can live with the constraint that the numbers must be whitespace-separated.
This includes a small bit of error checking:
int n = 0;
while( n < 1000 || n >= 10000 ) // check read integer fits desired criteria
{
cout << "enter 4 digit number: ";
cin >> n; // read the input as one integer (likely 10 digit support)
if( !cin.good() ) // check for problems reading the int
cin.clear(); // fix cin to make it useable again
while(cin.get() != '\n'); // make sure entire entered line is read
}
int arr[4]; // holder for desired "broken up" integer
for( int i=0, place=1; i<4; ++i, place *= 10 )
arr[i] = (n / place) % 10; // get n's place for each slot in array.
cout << arr[3] << " " << arr[2] << " " << arr[1] << " " << arr[0] << endl;

Minor sequence error in C++ program output

I am trying to output "states" for any binary number that is inserted (for each 0 it outputs a random number between 1 & max), for example 10100 should output 2, random number between 1 & 2, 3, random number between 1 & 3, random number between 1 & 3. Thus looking like 21323 or 223212 or 21313, etc. But the output my program is giving me is 23456 - why?
int main()
{
char binaryArray [0];
int c1=1;
int c0=0;
int i=0;
int n;
cout << "Enter length of binary: "; //Length = total number of 1s & 0s
cin >> n;
cout << "Enter binary number: ";
cin >> binaryArray;
cout << "States: ";
for(i; i<n; i++)
{
if(binaryArray[i]=1)
{
c1++;
cout << c1;
}
else if(binaryArray[i]=0)
{
c0++;
cout << rand()%c1+1;
}
/* if(c0 > c1)
{
cout << "Invalid Binary Representation.\n" << endl;
exit(0);
} */
}
system("PAUSE");
return 0;
}
When you have an array of 0 (that is: zero) characters, you cannot save anything in it, not even a single bit. Make that array "large enough" (whatever that means for you) or better use a std::string instead.
Oh, and compile your code with all compiler warnings enabled. When you have understood and fixed all these warnings properly, you program should work much better. (Hint: assignment inside conditional)
First of all, you have assignment in the if statements. Use == instead of =.
Second, if you expect the number to be entered as binary and stored in char array, use char when comparing. So, your if statements should be:
// vvvvvvv
if( binaryArray[i] == '1' )
{
c1++;
cout << c1;
}
// vvvvvvv
else if( binaryArray[i] == '0' )
{
c0++;
cout << rand()%c1+1;
}
Third, change the size of your array:
char binaryArray [0];
It must not be 0 here. Change it so something more common. Like 512, for example, if you think that this will be big enough.

Using C isdigit for error checking

While using the boolean check for the int num this loop doesn't work. The lines after it go unrecognized. Enter and integer like 60 and it just closes. Did I use isdigit wrong?
int main()
{
int num;
int loop = -1;
while (loop ==-1)
{
cin >> num;
int ctemp = (num-32) * 5 / 9;
int ftemp = num*9/5 + 32;
if (!isdigit(num)) {
exit(0); // if user enters decimals or letters program closes
}
cout << num << "°F = " << ctemp << "°C" << endl;
cout << num << "°C = " << ftemp << "°F" << endl;
if (num == 1) {
cout << "this is a seperate condition";
} else {
continue; //must not end loop
}
loop = -1;
}
return 0;
}
When you call isdigit(num), the num must have the ASCII value of a character (0..255 or EOF).
If it's defined as int num then cin >> num will put the integer value of the number in it, not the ASCII value of the letter.
For example:
int num;
char c;
cin >> num; // input is "0"
cin >> c; // input is "0"
then isdigit(num) is false (because at place 0 of ASCII is not a digit), but isdigit(c) is true (because at place 30 of ASCII there's a digit '0').
isdigit only checks if the specified character is a digit. One character, not two, and not an integer, as num appears to be defined as. You should remove that check entirely since cin already handles the validation for you.
http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
If you're trying to protect yourself from invalid input (outside a range, non-numbers, etc), there are several gotchas to worry about:
// user types "foo" and then "bar" when prompted for input
int num;
std::cin >> num; // nothing is extracted from cin, because "foo" is not a number
std::string str;
std::cint >> str; // extracts "foo" -- not "bar", (the previous extraction failed)
More detail here:
Ignore user input outside of what's to be chosen from