I have simple task concerning 'new' operator. I need to create array of 10 chars and then input those chars using 'cin'. Should it look like this ? :
char c = new char[10];
for(int i=0; i < 10; i++)
{
cin >> char[i] >> endl;
}
I have simple task concerning 'new' operator. I need to create array of 10 chars and then input those chars using 'cin'. Should it look like this ? :
char c = new char[10];
for(int i=0; i < 10; i++)
{
cin >> char[i] >> endl;
}
No need for endl
. And don't forget to delete []
the array at the end
char *c = new char[11]; // c should be a pointer.don't forget space for null char.
// do error checking.
cin >> c; // you can read the entire char array at once.
cout<<c<<endl; // endl should be used with cout not cin.
delete[]c; // free the allocated memory.
Close.
char *c = new char[10];
for(int i=0; i < 10; i++)
{
cin >> c[i];
}
// free the memory here somewhere
Better yet, if you don't really need a pointer.... don't use one. Then you don't have to worry about memory leaks. (obligatory mention of smart pointers?)
char c[10];
for(int i=0; i < 10; i++)
{
cin >> c[i];
}
Or... as others mentioned... read the whole 10 chars in at once. The difference is that with this solution spaces are accepted, with cin >> c
spaces are treated as delimiters IIRC.
To explain above answers, the "char*" is there because it says that the "c" variable will be a pointer. You need that, because "new" allocates some memory in heap and return a pointer to it. The "delete[]" operator is used to deallocate memory allocated using the new operator, so it will be avalaible to the system. The square brackets mean that the pointer that you will deallocate points to an array and that not just one piece of memory with size sizeof(char) should be deallocated, but that there is an arrays which should be deallocated completeley.
Since nobody has done yet, I'll suggest you use std::string
instead:
std::string word;
std::cin >> word; // reads everything up to the first whitespace
or
std::string line;
std::getline(std::cin,line);
The advantage of using std::string
is that it expands automatically, eliminating buffer overflows. If instead you deal with naked character buffers
void f()
{
char buffer[10];
std::cin >> buffer;
//
}
and someone comes along and enters more than 10 characters, then if you are lucky, the whole thing blows up immediately. (If you are unlucky, everything appears to keep working until some "funny" errors manifest much later, probably in seemingly unrelated sections of your code.)