how to store an input into an array? C++ - c++

int b;
int array[12];
cout << "Enter binary number: ";
cin >> b;
(for example: b will be 10100)
** How to store b(10100) into an array so that it'll be [1][0][1][0][0] **
cout << array[0] << endl;
** output should be 1 **
cout << array[1] << endl;
** output should be 0 **
Please help thank you.

A string can also be treated as an array of chars. So you can get input into a string, instead, and the cout statements you wrote, should work. However, they will be chars and not ints, so you would be storing '1' and '0' instead of 1 and 0. Converting between them is easy, just use array[0]-'0'
#include <string>
#include <iostream>
using namespace std;
int main()
{
string array;
cout << "Enter binary number: "; cin >> array;
// Suppose the user inputs 10100
cout << array[0] << endl; // outputs '1'
cout << array[1] << endl; // outputs '0'
cout << array[2] << endl; // outputs '1'
return 0;
}
Update: Added compilable code. Note that this is pretty much the original code posted with the question, except for inputting a string.

I had originally wrote up an answer similar to Pablo, but seeing as he already posted it, here is one more consistent with the information given.
It takes an int input and places it into an int array.
#include <iostream>
#include <cmath>
int main( )
{
int b;
int numDigits;
// Get bit string int
std::cin >> b;
// Get the number of digits
numDigits = std::floor( std::log10( ( float )std::abs( b != 0 ? b : 1 ) ) ) + 1;
// Dynamically create a new array of the appropriate size
int* arr = new int[ numDigits ];
// Initialize all the blocks of memory
std::memset( arr, 0, numDigits );
// Fill the array
for( int i = 0; i < numDigits; i++ )
{
arr[ numDigits - i - 1 ] = b % 10;
b /= 10;
}
system( "PAUSE" );
// Delete the array
delete [] arr;
return 0;
}
This one dynamically sets the size of the array so it fits correctly.

The following example stores bits to a raw C-style array as you require. But you can replace it with a std::vector if you want.
int main()
{
// assume sizeof(int) is 32, or you can use heap-allocated array or std::vector
int array[32];
unsigned int mask = 1;
// mask is initially 0x80000000
mask = mask << (sizeof(int)*8 - 1);
int i = 0;
// we start counting from the first "1",
// preceding "0"s are ignored to display
bool started = false;
int b;
cin >> b;
while (mask != 0)
{
// if current bit is "1" or "0"
if (mask & b)
{
started = true;
array[i++] = 1;
}
// if current bit is "0" and counting started
else if (started)
{
array[i++] = 0;
}
// ready to test next bit
mask = mask >> 1;
}
// test result
for (int j = 0; j < i; ++j) cout << array[j];
cout << endl;
return 0;
}
Test cases:
1. b = 8 => array: 1000
2. b = -8 => array: 11111111111111111111111111111000
3. ..

You can use boots dynamic bitset
#include "boost/dynamic_bitset.hpp"
#include <sstream>
#include <iostream>
int main()
{
boost::dynamic_bitset<> val;
std::stringstream input("1010101010");
input >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}
If you don't have boost use the std::bitset.
The only problem with std::bitset it has a fixed size
#include <bitset>
#include <sstream>
#include <iostream>
int main()
{
std::bitset<16> val; // fixed 16 bit size
std::cout << "Enter binary number:\n";
std::cin >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}

STORING A BINARY NUMBER INTO AN ARRAY
char binaryArray [5]; // The array looks like this: [][][][][]
cout << "Enter binary number: ";
cin >> binaryArray; // Stores the binary number into the array: [1][0][1][0][0]
cout << binaryArray[0] << endl; // The first element is sent to standard output.
cout << binaryArray[1] << endl; // The second element is sent to standard output.
For your input the output will be:
1
0
Here we have an array of characters. We input the binary number into the array and then we print each element of the array to display each bit. The first print line accesses the first element [1] [0] [1] [0] [0]. The second print line accesses the second element [1] [0] [1] [0] [0].
Let's say we had a binary number with 100 characters. The way that we output each element of the array would take a long time.
1.) Can you think of a more efficient way of printing out the contents of our array?
2.) How can we ensure that the user is inputting only ones and/or zeroes?

Related

save values from strigng array in 2d int array?

I have been taking a voluntary computer science course at school share for 1 month and want to practice something. Task:
I am to store a series of numbers with symbols in a string array for the first time. The numbers are to be stored in a two-dimensional int array. But the symbols should look different on output. And the output should be done only using the values of the int array. The numbers are one-digit. There is no need to check if the user makes the input correctly.
This is how the program should look like when it is executed:
Input:
.1.2.3.|.4.5.6.|.7.8.9
-------|-------|-------
Output:
;1;2;3;//;4;5;6;//;7;8;9
=======//=======//=======
I know that you always have to proceed in small steps. I have made it so far that the input is output exactly the same again. I just can't get the solution, I have been sitting here for hours. How do I save the numbers I have saved to the string array to the 2d array? And how do I replace the symbols to look like the example?
My code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int ArrayTwo[3][2] = {0}; //From Task
string ArrayInput[2] = {""}; //From Task
cout << "Input:" << endl;
for (int i = 0; i < 2; i++)
{
cin >> ArrayInput[i];
}
cout << "Output" << endl;
for (int i = 0; i < 2; i++)
{
cout << ArrayInput[i] << endl;
}
system("pause");
return 0;
}
Probably it's simplest to iterate to simply iterate through the input string and convert anything that's a digit to a number:
#include <cctype>
...
void PrintInner(int (&inner)[3])
{
std::cout << ';';
for (auto element : inner)
{
std::cout << element << ';';
}
}
...
int ArrayTwo[3][3];
string ArrayInput[2];
...
auto readPos = ArrayInput[0].cbegin();
for (auto& inner : ArrayTwo)
{
for(auto& element : inner)
{
// skip non-digit chars
while(!std::isdigit(*readPos))
{
++readPos;
}
element = *readPos - '0'; // char codes of digits 0123456789 are next to each other
++readPos;
}
}
cout << "Output" << endl;
PrintInner(ArrayTwo[0]);
for (int i = 1; i != 3; ++i)
{
std::cout << "//";
PrintInner(ArrayTwo[i]);
}
...
Demo on godbolt
In case you're unfamiliar with this: for ( ... : ...) is a ranged for-loop; this sets the loop variable to the elements of the array in increasing order of indices.

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.

filling a char array with a string? c++

I need to fill this array via user prompt. I was thinking to read in the user entry to a string and then assign that string to the array but that doesn't seem to be the right way to approach this. Could someone help me out?
The error I'm receiving reads "array type array[100] is not assignable"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
int main()
{
string theString;
char array[100]; // ARRAY MAX SIZE
int length = sizeof(array)-1;
char * ptrHead = array;
char *ptrTail = array + length - 1;
//USER PROMPTS & ARRAY FILL
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
array= theString;
//WHILE LOOP SWAPPING CHARACTERS OF STRING
while (ptrHead < ptrTail)
{
char temp = *ptrHead;
*ptrHead = *ptrTail;
*ptrTail = temp;
ptrHead++;
ptrTail--;
}
cout << array << endl;
return 0;
}
arrays are not assignable. You should use strcpy here:
But for this you'll have to convert theString to C like string.
strcpy(array, theString.c_str() );
Then adjust your ptrTail pointer too , like following :
int length = theString.size();
char *ptrTail = array + length - 1;
See Here
cin >> array; should put the input directly into the array, which I'm guessing is what you want
Also, there's a problem in your string reversal logic. You are reversing the entire array, not just the part that has been filled, which will put the filled portion at the end of the array. Consider using a function like strlen() to find out how long the actual input is.
You can copy the string to the array with strcpy or input the data directly to the array with cin >> array, but the better solution would be just not to use a char array, just use the string in your algorithm. That is also a better solution because you can overflow a fixed size char array
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
for (unsigned int i = 0; i <= theString.size() / 2; ++i)
swap(theString[i], theString[theString.size() - 1 - i);
cout << theString<< endl;
Edit
The same using pointers:
std::cout << "Please enter a string to be reverse: " << std::endl;
std::cin >> theString;
char* i = &theString[0];
char* j = &theString[theString.size() - 1];
for (; i < j; ++i, --j)
std::swap(*i, *j);
std::cout << theString << std::endl;

Fibonacci series in C++ can't get more than 47 numbers

I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}

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.