Reputation: 51
char binarycode[5][5];
string tmp;
cout<<"Please type first 5 binary numbers: ";
cin>>tmp;
char tmp2[5];
strcpy(tmp2, tmp.c_str());
binarycode[0] = tmp2;
This is my code for me to save the empty char array with user input string. So there will be 5 string that will break up to one dimension char array and will be saved to each row of binarycode. Howerver, it does not seems to work like Java where i can just store the one dimension array to two dimension array. Are there any way to make this process easier or is making method is better?
Upvotes: 0
Views: 1129
Reputation: 14589
The strcpy(0 function copies entire c-string to memory position you designated as destination. In code
char tmp2[5];
strcpy(tmp2, tmp.c_str());
In code
binarycode[0] = tmp2;
you attempted to save pointer - address of that buffer to a byte.
you statically allocated 5 bytes(!) of memory, then attempted to copy string to that memory. If anything, you would cause memory corruption this way, because rest of string would go somewhere.
C++ is not Java and you should thoroughly read books on this language, about syntax and standard you're using, not relying on something that "looks like". There are even principal differences between C and C++ in some areas.
If anything, iostreams provide all tools you need to get values from user input, but "proper" way to do requires handling cases of incorrect input. Consider this function:
#include <limits>
#include <iostream>
char getChar()
{
while (1) // Loop until user enters a valid input
{
std::cout << "Enter a byte value: ";
int x; // if we'll use char, cin would assume it is a character
std::cin >> x;
if (std::cin.fail()) // has a previous extraction failed?
{
// let's handle the failure
// or next >> will try parse same input
std::cout << "Invalid input from user.\n";
std::cin.clear(); // put us back in 'normal' operation mode
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
// and remove the bad input
}
//else if ( ((char)(x & 0xff)) != x ){
else if(( x > std::numeric_limits<char>::max()) ||
( x < std::numeric_limits<char>::min()))
{
// char can be from -127 to 127, it's one byte..
// int is allowing large values
std::cout << "Invalid value.\n";
}
else // nope, so return our good x
return (char)(x & 0xff);
}
}
The char is a pain in the backside with std::iostream, it always should be an int instead. Casting to smaller variable, like (char)x might be an undefined behavior, so need to mask larger values (char)(x & 0xff); For other types this function can become a template based on the type requested.
Now we should make it understand binary input? there is no predefined manipulator for binary format, you must input a string, validate it, and convert yourself.
int binaryToDec(std::string number)
{
int result = 0, pow = 1;
for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
result += (number[i] - '0') * pow;
return result;
}
std::string validateEntry()
{
bool valid = true;
std::string tempStr;
do
{
valid = true;
getline(std::cin, tempStr);
for (int i = 0; i < tempStr.length(); i++)
{
if ((tempStr.compare(i, 1, "0") != 0) && (tempStr.compare(i, 1, "1") != 0))
{
valid = false;
std::cout << "Enter Valid Binary Number: ";
break;
}
}
} while (valid == false);
return tempStr;
}
Use those in pattern:
std::cout << "Enter Binary Number: ";
std::string binaryString = validateEntry();
int binaryNum = binaryToDec(binaryString);
Upvotes: 0
Reputation: 7905
Your objective is to take a 1 dimensional array with size T and to populate or convert it to a 2 dimensional array with size MxN. What you will need to do in order to construct this algorithm before writing any code implementation is you will need to know before hand the sizes or lengths of both M and N and in your case you have explicitly expressed that it will be a 5x5 in size; T shouldn't matter in this case. M will be the size of your rows, where N will be the size of your columns. To do this you will need to traverse the single array for its size and then depending on its indexed value it should correspond to a (m,n) value. Another words you need to map A(n) to B(m,n).
The method that you are trying to achieve which is not the simplest or even the most efficient but mimics the algorithm mathematically would be as follows:
#include <iostream>
#include <string>
int main() {
char binaryCode[5][5] { 0 }; // Initialize to all 0s
char temp;
int row = 0;
int col = 0;
do {
std::cout << "Enter 5 binary number: ";
std::cin >> temp;
for ( ; col < 5; col++ ) {
binaryCode[row][col] = temp[col];
}
col = 0;
temp.clear();
row++;
} while( row < 5 );
row = 0;
col = 0;
std::cout << "\nResults:\n";
for ( ; row < 5; row++ ) {
for ( ; col < 5; col++ ) {
std::cout << binaryCode[row][col] << " ";
}
std::cout << "\n";
col = 0;
}
return 0;
}
However this first approach is a little naïve and as P0W already stated with his answer:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> binaryCodes;
binaryCodes.reserve( 5 );
std::string tmp;
for ( int i = 1; i <=5; ++i ) {
std::cin >> tmp;
binarycode.push_back ( tmp );
}
return 0;
}
Is cleaner and simpler and does exactly the same thing that you would need.
Upvotes: 0
Reputation: 47784
Are there any way to make this process easier or is making method is better?
Consider using std::vector
of std::string
like std::vector < std::string > binarycode ;
Then,
binarycode.reserve( 5 );
std::string tmp;
for ( int i = 1; i <=5; ++i )
{
std::cin >> tmp;
binarycode.push_back ( tmp );
}
Upvotes: 5