basic cin issue.

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  //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;
		

}
Last edited on
http://en.cppreference.com/w/cpp/io/basic_istream/getline

Your problem is that the failbit is set when the input is longer than you ask for. You need to clear the stream. Something like this:

1
2
3
4
5
    if (!(cin.getline(IA.main, sizeof IA.main)))
    {
        cin.clear();
        cin.ignore(std::numeric_limits<int>::max(), '\n');
    }
Last edited on
> main[20] = mv[20];
out of bounds access
ne555 could you elaborate? Would useing arrays in this manner not be a proper method of codeing?

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.
Topic archived. No new replies allowed.