Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help with Simple C++ code please

  1. Mar 6, 2009 #1
    Help with Simple C++ code please :)

    So here is the idea of the program (I have comments in the code too)

    Ask the user for a number up to 5 digits long, store it in a as a string array,reverse the order
    of the number (i.e. if user enters 12345 make it 54321), convert the reversed string to an int type object, calculate the sqrt of the reversed number.

    here is:

    Code (Text):
    //
    // GEU 111
    // Spring09
    //


    /* Program to:  Prompt user for a five-digit integer, reverse the order of the digits,
     compute the sqrt of both the digit and the reversed digit      */

    #include <iostream>
    #include <cmath>
    #include <cstring>
    using namespace std;

    int main ()

    {
        char nString[5];
        char rString[5];
        int L;
        cout << "Please enter a string of up to five digits \n";
       
       
        cin.getline (nString, 6 ,'\n');  //Takes up to 5-digit string from user
       
        L = strlen (nString);            // Determines length of string entered
       
        cout << "The number you entered is " << nString << endl << endl; //outputs string
       
       
       
        for (int i=L; i<L; i++)
        {
             rString = nString[L-1-i]; // reverses nString     ERROR OCCURS ON THIS LINE
        }
       
        atoi (rString);                 // Converts char rString to int nString
       
        cout << rString << endl << endl;

        system ("PAUSE");
        return 0;

    }




    /* OUTPUT:                         */
     
    here is the compiler error message:

    Code (Text):
     line 34 D:\1NEU SPRING 09\GEU 111 FLASH\HW\hw7b_cpb.cpp incompatible types in assignment of `char' to `char[5]'
    it occurs on the one-line block of code in the for loop
     
  2. jcsd
  3. Mar 6, 2009 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    "rString = nString[L-1-i]"
    you are trying to copy a single char out of nString into the whole of rString

    Assuming you want to do it in this 'c' way, I suspect you meant rString
     
  4. Mar 6, 2009 #3
    Re: Help with Simple C++ code please :)

    Okay cools... so I changed it to

    rString = nString[L-1-i]

    and I get no compiler errors. But I do get garbage back when I run it. Watch what happens when I enter 12345

    Code (Text):
    Please enter a string of up to five digits
    12345
    The number you entered is 12345

    ¶╕├wx$>

    Press any key to continue . . .
     
    ¶╕├wx$> this is supposed to be the reversed string converted to a number

    Edit: Do I need to redefine the rString object type somewhere? Or shouldn't atoi take care of that?
     
    Last edited: Mar 6, 2009
  5. Mar 6, 2009 #4

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    you defined rstring as a 5 element char array at the start
    Try something like
    for (int i=0;i<L;i++)
    to = from[(L-i)-1];
    }

    Remember to terminate the to[] array
    ps. How many characters can you fit in char array[5] (hint it's not 5!)

    pps. any reason you aren't using std:string if this is c++?
     
  6. Mar 6, 2009 #5
    Re: Help with Simple C++ code please :)



    Except for the names, I don't see the diff between your for loop and mine.

    What do you mean "terminate" the to[] array ? Sorry I am new to the whole programming thing

    ps. oh yeah 4. So I changed them to 6.

    as for pps. I don't know what that means. But i thought that was taken care of under
    #include <cstring>
    using namespace std;
     
  7. Mar 6, 2009 #6

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    You start counting from the end (5) and write into position 5 of the 'to' array - which is beyond the size of the memory you have reserved.
    Try drawing the to and from strings out on graph paper and see where you should be writing.
    'C' strings have to have a zero at the end, so you need to set "to[5]=0" to make it a real string. C++ has it's own string type which handles memory an termination for you.
     
  8. Mar 6, 2009 #7
    Re: Help with Simple C++ code please :)

    Look again:

    for (int i=L; i<L;? i++)
    {
    rStringwhat's missing here? = nString[L-1-i]this is not the same as what mgb_phys is suggesting; // reverses nString ERROR OCCURS ON THIS LINE
    }
     
  9. Mar 7, 2009 #8
    Re: Help with Simple C++ code please :)

    Here's the revised thus far. I drew out the arrays and I am still missing your point mgb_phy

    Code (Text):
    #include <iostream>
    #include <cmath>
    #include <cstring>
    using namespace std;

    int main ()

    {
        char nString[6];
        char rString[6];
        int L;
        cout << "Please enter a string of up to five digits \n";
       
       
        cin.getline (nString, 6 ,'\n');  //Takes up to 5-digit string from user
       
        L = strlen (nString);            // Determines length of string entered
       
        cout << "The number you entered is " << nString << endl << endl; //outputs string
       
       
       
        for (int i=0; i<L; i++)
        {
             rString[i] = nString[(L-1)-i]; // reverses nString
        }
       
        atoi (rString);                 // Converts char rString to int nString
       
        cout << "Your number reversed is " << rString << endl << endl;

        system ("PAUSE");
        return 0;

    }
    I don't see what is wrong with my memory allocation?

    I defined all strings to be at most 6 characters, including the null character.

    Then it should read the actual length of the string. And then swap the characters into rString....
     
    Last edited: Mar 7, 2009
  10. Mar 7, 2009 #9
    Re: Help with Simple C++ code please :)

    I'm just going to add some code to help you debug the problem:





    Just print debug statements where you suspect the problem.

    You loop is bit weird. say L=5

    for (int i =5; i<5; i++)
    {
    }

    you start with 5, and you have condition that says i is less than 5?
     
  11. Mar 7, 2009 #10

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    "for (int i=L; i<L; i++)"
    This means start with i=5 then while i is less than 5 increment i
    So the loop never runs, which is a good thing because doing rString[6] will crash the program.
     
  12. Mar 7, 2009 #11
    Re: Help with Simple C++ code please :)

    Ookay, so I changed it to for (int i=0; i<L;i++)

    This partially resolves my issue.

    This is the output for entering 123:

    Code (Text):
    Please enter a string of up to five digits
    123
    The number you entered is 123

    Your number reversed is 321wx$>
     
    It is still reading the empty characters. How can I "word" the code so that it does not?
     
  13. Mar 7, 2009 #12
    Re: Help with Simple C++ code please :)

    I can suggest
    1) Having 00321 (so before the reverse append 0s to the end.. so 12300)
    2) Use
    cout<<"this is .. ";

    for (int i=0; i<L;i++)
    cout <<stringArray;

    cout<<" ..." <<endl;
     
  14. Mar 7, 2009 #13
    Re: Help with Simple C++ code please :)

    When I use the function: strlen (nString)--> it reads how long the array is.

    Now if I allocate an array of length [6] and then only enter 3 integers to be stored then there are 3 "empty" spaces.

    When I use strlen () does it include the "empty spaces" ?

    Edit: This falls in line with what rootX said, but no I cannot do it like that i.e., if the number entered is less than 5 characters long (+ the null) I cannot have it cout zeros in front of the number. Good idea though ... maybe it can be modified to suit my needs.
     
  15. Mar 7, 2009 #14
    Re: Help with Simple C++ code please :)


    Anyone know how I can resolve this issue? How can I tell it then when it reverses the string to not include the empty spaces?
     
  16. Mar 7, 2009 #15

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    You have to terminate the string.
    'C' strings are an array of characters ending with a zero
    so after the last character you write into the string you have to write a 0, thi sis what strlen() and the print statement use to work out when it ends, the "wx$" is just whatever happens to be in memory next.

    A common safety strategy is to set the entire string memory to zero after you allocate it. eg:
    char string[6];
    memset(string,0,6);

    Then as long as you write less than 6 chars it will always be a valid string.
     
  17. Mar 7, 2009 #16
    Re: Help with Simple C++ code please :)

    Unfortunately, when I enter "123" ... I get the same nonsense characters back

    Code (Text):
    Please enter a string of up to five digits
    123
    The number you entered is 123

    Your number reversed is 321wx$>

    Press any key to continue . . .

     


    Code (Text):

    #include <iostream>
    #include <cmath>
    #include <cstring>
    using namespace std;

    int main ()

    {
        char nString[6];
        memset(nString,0,6);
        char rString[6];
        int L;
        cout << "Please enter a string of up to five digits \n";
       
       
        cin.getline (nString, 6 ,'\n');  //Takes up to 5-digit string from user
       
        L = strlen (nString);            // Determines length of string entered
       
        cout << "The number you entered is " << nString << endl << endl; //outputs string
       
       
       
        for (int i=0; i<L; i++)
        {
             rString[i] = nString[(L-1)-i]; // reverses nString
        }
       
        atoi (rString);                 // Converts char rString to int nString
       
        cout << "Your number reversed is " << rString << endl << endl;

        system ("PAUSE");
        return 0;

    }
     
    Edit: I put memset after both strings and it worked! I do not understand why it has to go after BOTH since rString is just made up from the elements of nString?

    Thanks for all of your help by the way mgb_phys
     
  18. Mar 7, 2009 #17

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    You need to manually terminate rString because you are copying characters into it one at a time, the language doesn't know when you have finished - you can copy data into any element of rString in any order

    The << command will terminate nString for you because it knows when the input has finished.

    You only have to do this for 'C', c++ as a string object that handles all these details for you
     
  19. Mar 8, 2009 #18
    Re: Help with Simple C++ code please :)

    I am confused now. Aren't I in C++ ? Or did by using #include<cstring> did I use 'C' instead?

    My professor doesn't tell us what we are doing really; he just shows us how to do certain tasks.

    Is that why you asked

    I would like to see how to do it that way. Is it just a simple substitution for a line somewhere? Or would I have to redo the entire code?
     
  20. Mar 8, 2009 #19

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Re: Help with Simple C++ code please :)

    You are writing in C++ ( the << operator) but all the other stuff, using char string[] and ato() etc are all raw 'C'.
    There is always a problem with these sort of homework questions, because in reality you would use higher level C++ features like std:string but they may want you to use raw
    C strings to get an understanding of the memory
     
  21. Mar 8, 2009 #20
    Re: Help with Simple C++ code please :)

    I see. (no pun).

    I did not know that "<<" was even an 'operator' ! I don't even know what that means :confused:

    Is "<<" exclusive to C++ ?

    Also, do know of any good C++ books? Most of the books I have dealt with just show you how to solve some problems using C++.

    I would love it if there was a relatively "easy-to-read" book on what is actually going on here.
    That's probably asking to much though. :smile:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Help with Simple C++ code please
  1. C++ Code Help (Replies: 3)

  2. FFT code help please (Replies: 16)

Loading...