If you wrote in your other program
1 2
|
cin >> word[256];
cout << word[256] << endl;
|
you instructed the compiler to read only one letter. If "word" is an array of characters, word[0], word[1], ... word[255] are individual characters. So, your program behaved like a program
1 2 3
|
char letter;
cin >> letter;
cout << letter << endl;
|
Note, though, that for an array of size 256, the valid indexes are 0..255. When you wrote to word[256], you wrote to memory just outside the array. Some compilers may halt your program for that, but in general, C++ does not check this error, and undefined results may occur.
what 256 meant, im guessing its just the max size of what you input.
No, it is only the size of the array. The max size of what you input would be set with setw() in this case:
1 2
|
char word[256];
cin >> setw(3) >> word; // try entering a word that's longer than "dog"
|
in fact, you should never write to an array without a set limit, a program with
cin >> word
can be trivially hacked to execute any malicious code.
Normally, to deal with strings in C++, strings (nor arrays of char) are used, which are more appropriate for the task (among other things, they are free of that particular vulnerability, since they automatically resize to accomodate the input)
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
string word;
cin >> word;
cout << word << endl;
system("pause");
}
|