Note that there are some explanatory texts on larger screens.

plurals
  1. POI get a number 2 when I reverse my string
    primarykey
    data
    text
    <p>I wrote this code to reverse strings. It works well, but when I enter short strings like "american beauty," it actually prints "ytuaeb nacirema2." This is my code. I would like to know what is wrong with my code that prints a random 2 at the end of the string. Thanks</p> <pre><code>// This program prompts the user to enter a string and displays it backwards. #include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; void printBackwards(char *strPtr); // Function prototype int main() { const int SIZE = 50; char userString[SIZE]; char *strPtr; cout &lt;&lt; "Please enter a string (up to 49 characters)"; cin.getline(userString, SIZE); printBackwards(userString); } //************************************************************** // Definition of printBackwards. This function receives a * // pointer to character and inverts the order of the characters* // within it. * //************************************************************** void printBackwards(char *strPtr) { const int SIZE = 50; int length = 0; char stringInverted[SIZE]; int count = 0; char *strPtr1 = 0; int stringSize; int i = 0; int sum = 0; while (*strPtr != '\0') { strPtr++; // Set the pointer at the end of the string. sum++; // Add to sum. } strPtr--; // Save the contents of strPtr on stringInverted on inverted order while (count &lt; sum) { stringInverted[count] = *strPtr; strPtr--; count++; } // Add '\0' at the end of stringSize stringInverted[count] == '\0'; cout &lt;&lt; stringInverted &lt;&lt; endl; } </code></pre> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload