#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
int main() {
//initialising the char array and vector
char sentence[30] = {};
vector<string> words{"The", "only", "thing", "to", "fear", "is", "fear", "itself"};
//For loop iterates through the vector and adds the converted strings to the char array
for(int i = 0; i < words.size(); i++){
//if statements check if there is overflow and breaks the loop if there is
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds the strings from words to sentence one at a time
strcat(sentence, words[i].c_str());
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds a space in between each word in the cstring
strcat(sentence, " ");
}
//couts the full sentence and the length of sentence
cout << sentence << " " << strlen(sentence) << endl;
cout << sentence[29] << endl;
return 0;
}
I commented out my if statements that break if the array goes above 30 elements but now its returning 38. When I try accessing the elements above what the array can hold, it still gives me an error. Shouldn't the compiler throw an error as soon as the number of elements in the array goa above 30? I am pretty new to C++ so I am not sure if this is something with the language itself or something on my end. any help is appreciated.