C/C++ Help with Simple C++ code please

  • Thread starter Thread starter Saladsamurai
  • Start date Start date
  • Tags Tags
    C++ Code
AI Thread Summary
The discussion centers on troubleshooting a C++ program designed to reverse a user-inputted five-digit number and calculate its square root. Initial errors stemmed from incorrect array assignments and memory management, particularly in copying characters and terminating strings properly. Suggestions included using `memset` to clear memory and ensuring the reversed string is null-terminated. The conversation also highlighted the potential benefits of using C++'s `std::string` for easier string manipulation instead of raw C-style strings. Ultimately, participants emphasized understanding memory management and string handling in C++.
Saladsamurai
Messages
3,009
Reaction score
7
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:
// 
// 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:
 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
 
Technology news on Phys.org


"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
 


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:
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:


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


mgb_phys said:
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++?


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;
 


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.
 


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

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
}
 


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

Code:
#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:


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


cout<<"starting loop. L value is "<<L<<endl;
for (int i=L; i<L; i++)
{
rString = nString[(L-1)-i]; // reverses nString
cout<<nString[(L-1)-i]<< " is assigned to rString"<<rString<<endl;
}
cout<<"loop ended"<<endl;



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?
 
  • #10


"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.
 
  • #11


mgb_phys said:
"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.

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:
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?
 
  • #12


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;
 
  • #13


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.
 
  • #14


Saladsamurai said:
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.


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?
 
  • #15


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.
 
  • #16


mgb_phys said:
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.

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

Code:
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:
#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
 
  • #17


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
 
  • #18


mgb_phys said:
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

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

any reason you aren't using std:string if this is C++?

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?
 
  • #19


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
 
  • #20


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:
 
  • #21


use strrev inbuilt function to reverse the string, then use the math funtion sqrt
 
Back
Top