357mag 3 Posted Saturday at 10:21 PM Just one question about the way this program is working. I make a constant and initialize it to 10. I use that to make the size of the array called name1. What I don't understand though is if I run the program and enter in a long name that is longer than 10 characters, C++ still allows me to do it and the program works just fine. I was expecting an error message saying something about 'out of bounds error". I don't get why C++ is allowing me to enter in a name that is longer than the size of the array: #include<iostream> #include<cstring> using namespace std; int main() { const int SIZE = 10; char name1[SIZE]; char name2[SIZE] = "C++owboy"; cout << "Howdy! I'm " << name2 << "!"; cout << " What's your name?" << endl; cin >> name1; cout << "Well, " << name1 << " your name has "; cout << strlen(name1) << " letters" << endl; cout << "Your initial is " << name1[0] << endl; name2[3] = '\0'; cout << "Here are the first three characters of my name: "; cout << name2 << endl << endl; system("pause"); return 0; Share this post Link to post
Remy Lebeau 1442 Posted Saturday at 11:13 PM (edited) None of the operations you are doing perform any bounds checking. They don't even know the size of your buffers. Your code exhibits undefined behavior if your input overflows the buffers. To avoid this, use std::cin.get() or std::cin.getline(), which allow you to specify the buffer sizes. Or better, just use std::string instead of char[]. Edited Saturday at 11:17 PM by Remy Lebeau Share this post Link to post
David Heffernan 2354 Posted Sunday at 09:07 AM You might want to start with a beginners book to learn C++ that will take you through all of this learning. And you definitely don't want to be using character arrays when strings exist. Share this post Link to post