I created this program, yes. But I don 't understand how and why does it work? Why do I have to press enter only one time when I use "cin" in the loop?
Logically I would need to press enter after every letter...
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main()
{ char x[10000];
int t,i;
cout << "How many letters there will be ";
cin >> i;
i=i-1;
cout << "Enter a word: ";
for (t=0; t<=i; t++) {cin >> x[t];}
while (t>=0) {cout << x[t]; t--;}
}
you must write after the code, just before the last breace
"system ("pause");
return 0;"
or, even better:
"cin.ignore();
cin.get();
return 0;"
and then another error: just befor the while loop you have to type "t--;" because there t is bigger than the index of the last element of the string. Enjoy
So with this the for loop will run 3 times, on the first time it is only expecting to get 1 letter so it will only take the first letter we entered. But the "ey" are still in the buffer so on the next pass through the loop it doesn't ask for another input since there is still stuff in the buffer, so it just grabs the next letter in the buffer which is 'e' and stores it. Then after that the next loop grabs the third letter in the buffer which is 'y' and stores it.
Hope that makes sense, I would recommend looking into how I/O works and about buffers and buffer overflows.
Also another test that might help you understand it better is when you run the program after it asked you how many letters there enter the word a letter at a time. So "hey" would be entered like 'h' enter 'e' enter 'y' enter. This will provide the same result.
I think you should not ask how many letters a user are going to enter. The user can make a mistake. You should find the end of the inputed array yourself by searching the terminated zero. So it would be simpler to write
cin.getline( x, sizeof( x ) );
Also there are some default conventions about naming variables. If you are using a character array for storing string literals it is better to name it 's' instead of 'x'. Name 'x' is usually used for denoting objects of arithmetic types.