Help with Simple C++ code please

  • C/C++
  • Thread starter Saladsamurai
  • Start date
  • Tags
    C++ Code
In summary, this conversation is about a user seeking help with a simple C++ code. The program prompts the user for a number up to five digits, stores it as a string array, then reverses the order of the digits and converts it to an integer. The code includes comments and is designed to calculate the square root of both the original number and the reversed number. However, the user encountered a compiler error and received garbage output when running the code. After receiving suggestions from other users, the user made changes to the code, including using std:string instead of char arrays and properly terminating the string.
  • #1
Saladsamurai
3,020
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
  • #2


"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
 
  • #3


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


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++?
 
  • #5


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


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


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
}
 
  • #8


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


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
 

What is C++ code?

C++ is a high-level programming language commonly used to write complex computer programs. It is an extension of the C programming language and is known for its efficiency, flexibility, and powerful capabilities.

What does "Help with Simple C++ code" mean?

This phrase usually refers to a request for assistance with writing, understanding, or debugging a small and relatively straightforward C++ program. It could also mean asking for help with a particular concept or syntax in C++.

Why do I need help with Simple C++ code?

C++ can be a challenging language to learn and master, especially for beginners. It is not uncommon to need help with understanding concepts, troubleshooting errors, or optimizing code for efficiency.

Where can I get help with Simple C++ code?

There are many resources available for getting help with C++ code, including online forums, tutorial websites, and programming communities. You can also reach out to experienced programmers or seek assistance from a professional tutor or mentor.

How can I improve my understanding of Simple C++ code?

The best way to improve your understanding of C++ code is through practice and experimentation. Write your own programs, read through code written by others, and seek feedback and guidance from experienced programmers. Additionally, regularly learning new concepts and staying updated on the latest developments in the language can also help improve your understanding.

Similar threads

  • Programming and Computer Science
Replies
30
Views
2K
  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
5
Views
881
  • Programming and Computer Science
2
Replies
66
Views
4K
Replies
10
Views
956
  • Programming and Computer Science
3
Replies
73
Views
4K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
3
Replies
89
Views
4K
Back
Top