Hello, I'm playing with classes and constructors and I'm running into a cin issue. My current program works as long as I stay with in the specified amount of characters, if I exceed the max of 20 characters the program will not proceed correctly. What is an efficent method to ignore characters that exceed the maximum allowed?
//Testing classes, constructors and arrays.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class C_test
{
public:
//Two arrays.
char main[20]{};
char bx[50]{};
//constructor
C_test(char mv[20], char bv[20])
{
main[20] = mv[20];
bx[50] = bv[50];
}
C_test() = default;
};
int main()
{
C_test IA; //create class
cout << "Please enter a main value (IA)" << endl;
cin.getline(IA.main, sizeof IA.main, '\0');
//add code here to find the null character if the character array exceeds 20 characters remove and add the null statement.
cout << "Please endter a bx value (IA)" << endl;
cin.getline(IA.bx, sizeof IA.bx, '\0');
//add code here to find the null character if the character array exceeds 50 characters remove and add the null statement.
cout << "Main = " << IA.main << endl << "bx value = " << IA.bx << endl;
return 0;
}
When you do array[ index ] you are saying "access the element in the position `index' of the array"
valid values for `index' go from 0 to size-1. Using a value outside that range is an error (know as out of bounds access) and causes undefined behaviour.
There is no especial case for index==size.
There are no automagic check for the validity of the index.
To copy two arrays you need to traverse them and copy element wise.