Why does this char array do this?

Ok so ive never read any tutorials or info on this topic so it was just something i was trying out but how come when i use "word[256]" on the input and output the output only shows the first letter of any word i type (for example if i type dog i only see "d" as the output) and if i just use "word" i get the entire word that i type. Also i was wondering exactly what 256 meant, im guessing its just the max size of what you input.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    char word[256];

    cin >> word;

    cout << word << endl;
    system("pause");
}

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");
}
* Face palm* my bad i should have easily realized why the input and output was the single letter, and yes normally if this was simple input i would just use a string but like i said i was doing some experimenting. Thanks though this cleared it up for me :) and ill be sure to remember about 255
Last edited on
Topic archived. No new replies allowed.