Char ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
	cout << "how many words do you want to enter: ";
	int n;
	cin >> n;
	char a[n];
	cout << "enter: ";
	cin >> a; // cannot allocate an array of size 0, how can i say that n is > 0?
	if (...) {// I want to say that if the user wrote more words than 'n', return 0.
		cout << "you wrote too much letters " << endl;
		return 0 }
	else 
	cout << "you entered: " << a << endl;
	return 0;
	}

Please help!!
Either use some constant that specifies maximum possible lemgth of the array or use the standard class std::string.
Firstly, char a[n] is incorrect cause the value of n is NOT defined at compile time. You should get an error
I solved it :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

int main()
{
string a;
int n;
cout << "how many words do you want to enter: ";
cin >> n;
cout << "enter: " ;
cin >> a;
if ( a.length() < n || a.length() == n )
cout << "you entered: " << a << endl;
else 
cout << "you wrote too many letters" << endl;
return 0;
}
Topic archived. No new replies allowed.