Limit size of string (arrays and c-style strings)

Hi, how do I tell the if statement to output this error message 'exceeded the maximum amount of characters' that has its characters stored in an array using c-style string?

[INPUT] The cat caught the mouse!
[OUTPUT] Exceeded the maximum amount of characters (max 10)

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
#include<iostream>
#include<string>
#include <cstring> 
using namespace std;
int main()
{
	string text, save, final_output, reverse_word;
	int word_count(0), pos(0),length(0), count = 0;
	const int MAX = 10; // max number of characters on one line
	char input[MAX];
	int size;
	
	cout << "Enter a sentence: " << endl;
	cin.getline(input, MAX, '\n');

	if (size > MAX)
	{cout << "Exceeded the maximum amount of characters (MAX 100)";}
	else
	{
		while(input[count] != '\0')
		{
		input[count];
		count ++;
		}
		for (int i = 0; i < input[count]; i++)
		{}
	}
	
	cout << endl;
	system("PAUSE");
	return 0;
}
Why are you using a c-style character array when you are also using std::string? Don't use c-style arrays.
Use this code below:

1
2
3
4
5
6
7
8
if (cin.fail())
{
     cout << "Exceeded the maximum amount of characters (MAX 100)";
}
else
{
    ....
}


When calling cin.getline() and the input exceeds the specified buffer size, failbit is set.
See: http://www.cplusplus.com/reference/istream/istream/getline/

And the function to check if failbit is set is cin.fail() in your case.
See: http://www.cplusplus.com/reference/ios/ios/fail/
Topic archived. No new replies allowed.