Thread: Type casting an array (beginner)

  1. #1
    Registered User
    Join Date
    Feb 2013
    Location
    San Juan, PR
    Posts
    14

    Type casting an array (beginner)

    I'm having some problems with changing an array of numbers of type char to type int. Every time i try to sum 2 array indexed values it returns some letter or symbol. Also, if i change the type of the array in the functions the compiler gives me an error message. I would also like to add that the problem requires that the first two arrays be char so each individual number gets assigned to a different value.
    My current code is:
    Code:
    #include <iostream>
    
    void input(char a[], char b[], int& size_a, int& size_b);
    
    
    void convert(char a[], int size);
    
    
    void reverse(char a[], int size);
    
    
    void add(char a[], char b[], int c[], int size);
    
    
    int main()
    {
      using namespace std;
    
    
      char a[20], b[20];
      int c[20];
      int size_a, size_b;
    
    
      input(a, b, size_a, size_b);
    
    
      convert(a, size_a);
      convert(b, size_b);
    
    
      a[0] += b[0];
    
    
      cout << a[0] << " " << b[0] << endl;
    
    
      reverse(a, size_a);
      reverse(b, size_b);
    
    
      add(a, b, c, 3);
    
    
      cout << a << " " << b << " " << c << endl;
    }
    
    
    void input(char a[], char b[], int& size_a, int& size_b)
    {
      using namespace std;
    
    
      cout << endl
           << "Enter a number with up to 20 digits:\n";
      cin >> a;
      cout << "Enter the amount of digits it has.\n";
      cin >> size_a;
    
    
      cout << "Enter a second number to be summed to the first:\n";
      cin >> b;
      cout << "Enter the amount of digits it has.\n";
      cin >> size_b;
      cout << endl;
    }
    
    
    void convert(char a[], int size)
    {
      using namespace std;
    
    
      for (int i = 0; i < size; i++)
        {
          a[i] = static_cast <int> (a[i]);
        } 
    }
    
    
    void reverse(char a[], int size)
    {
      using namespace std;
    
    
      int b[size];
    
    
      for (int i = 0; i < size; i++)
        {
          b[i] = a[i];
        }
    
    
      for (int j = 0; j < size; j++)
        {
          a[j] = b[size - (j + 1)];
        }
    }
    void add(char a[], char b[], int c[], int size)
    {
      using namespace std;
    
    
      for (int i = 0; i < size; i++)
        {
          c[i] = a[i] + b[i];
    
    
          if (c[i] >= 10)
        {
          c[i] -= 10;
          c[i+1] += 1;
        }
        }
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Well, several problems I can see.

    Your input() function does not control how much input is accepted. If the user enters exactly 20 characters, the reading code will run past the end of your arrays (A string is marked by a character with value zero, so 20 characters of input actually place 21 characters into the array). There is also no way, with that code, of preventing a user entering MORE than 20 characters. Then, of course, there is potential for the user to enter (say) 5 characters, but enter the sizes as 37. Trusting the user is bad practice: your code needs to assume the user is NOT perfect, WILL do things contrary to your expectations, and therefore cope with such things.

    Second, the convert() function has absolutely no effect (except for potential undefined behaviour if size exceeds the actual length of the array). The line
    Code:
        a[i] = static_cast <int> (a[i]);
    where a[i] is of type char does absolutely nothing. It converts a[i] to an int (an operation that gives the same value, just of type int). Then it assigns that value back into a[i], which converts that value back to being a char. Assuming i is a valid index into the array, the net effect is no change whatsoever. This line certainly does not magically morph the array a so it is an array of ints.

    Third is your add() function. By adding character values up to a (user-supplied) size, it probably produces non-printable characters, which would explain part of your problem. It can also produce values that a char cannot represent, which means overflow. If char is a signed type for your compiler, that means undefined behaviour. If char is a unsigned type, the value will be wrapped around (modulo arithmetic). It is implementation-defined (aka compiler specific) whether char is a signed or an unsigned type. The most significant problem comes in if the user has entered wrong sizes .... interpreting character arrays as strings means I/O functions will output every character it finds until it encounters one with value zero. By adding values, you are potentially meaning there is no zero character within the arrays.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Location
    San Juan, PR
    Posts
    14
    Thanks for the valuable information. This program was actually the driver program i was using to make the functions one by one when i started the function add i found that the type cast i used didn't work. If i may ask, i'm not really sure which method would be better to change the size (for the functions parameters) according to the amount of string characters the user enters. Should i make another function to count the characters the user enters or can i just leave it as a large constant?
    Also, what would be the ideal method to convert the array from the type char to int so i can sum the numbers?

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The classical response is to use dynamic memory allocation. The problem with that is that "cin >> some_array_of_char;" always has potential to overrun the array. Users are like that. Making the array larger just makes the user have to work harder (or more stupidly).

    Two possible approaches (there are others).

    1) Use cin.getline() with an array of char.
    Code:
    #include <iostream>
    
    // and in a function somewhere
    
    char buffer[21];
    std::cin.getline(buffer, 21);
    which will read up to a newline, or to 21 characters (including zero terminator), whichever comes first. Additional characters on the line will be read on subsequent operations.

    2) Use the C++ string (from the C++ standard library).
    Code:
    #include <iostream>
    #include <string>
    
    // and in a function somewhere
    
    std::string buffer;
    std::getline(std::cin, buffer);
    The advantage of this approach is that buffer, since the std::string type dynamically manages memory behind the scenes, will be able to hold any size input (up to limits of the host system, anyway).

    In both cases, check the state of cin to see if an error occurred in reading.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    There is also a third option, use the setw() manipulator to limit the number of characters the extraction operator>> will extract.

    Code:
    char buffer[21];
    cin >> setw(21) >> buffer;
    This will read at most 20 characters from the stream. It also stops processing when it encounters a space. The end of string character is always appended to the characters read. Also never rely on the user telling you how many characters are in a string.

    I usually recommend using getline() with a std::string to get the data from the stream, then use stringstreams to process that complete line if necessary.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Advantages of c++ type casting over c type casting
    By kaibalya2008 in forum C++ Programming
    Replies: 10
    Last Post: 05-05-2009, 11:09 AM
  2. about type casting...
    By ZeroMemory in forum C Programming
    Replies: 17
    Last Post: 10-01-2008, 08:24 AM
  3. difference between type conversion and type casting
    By Bargi in forum C Programming
    Replies: 1
    Last Post: 01-23-2007, 03:17 AM
  4. Type Casting
    By joshdick in forum C++ Programming
    Replies: 6
    Last Post: 09-06-2003, 08:30 PM
  5. Type Casting?
    By Megatron in forum C++ Programming
    Replies: 3
    Last Post: 08-15-2002, 01:07 PM