0
        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?

3
  • 1
    Seeing strcpy in code like this is discouraging. If you're doing C++, please, please use std::string. The strcpy function is notoriously problematic. In this short example you have a gigantic buffer-overflow bug which is why it's really a bad idea to even start down this road. Commented Jan 27, 2017 at 6:27
  • Howerver, it does not seems to work like Java -- C++ is not Java. Don't use Java as a model in writing good C++ code. If you continue falling back on using "Java techniques" in a C++ program, your program will either have one or more of these things -- 1) have bugs, 2) be coded inefficiently, 3) have memory leaks 4) just look plain weird to a C++ programmer. Commented Jan 27, 2017 at 6:36
  • it's unclear what you want to achieve, question describes incorrectly stated problem and tries to solve it with incorrect code. Is it "how to save user input data" or "How to save user input done in binary format?" See my answer below, both variants covered Commented Jan 27, 2017 at 7:50

3 Answers 3

5

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 );
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is very good alternative code but I am trying not to use code that I am not familiar with. So can you give other solution?
@YeramHwang Sorry, then I'd suggest get yourself familiar with it. Its probably not the best code snippet, but no matter you're a student or a professional you should always thrive for good solutions. And what was "Are there any way to make this process easier or is making method is better?" all about ? ( Don't edit your post now :-| )
@YeramHwang: Your attempt shows quite clearly that you are not familiar with the tools you used. So it's not a choice between something you are familiar with and something you aren't, but between two things you are not familiar with. It is no question that you should familiarize yourself with the better solution. You'll even have a head start with that, as you don't need to first unlearn any misconceptions as you need to for the worse way.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.