trying to limit the string input

Right now I am trying to limit the input of the string for this zip code evalulator. but I think I am doing
string str (5); this part wrong. can some explain what is wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;
 
int main ()
{
  int zip;

  string str (5);
  cout << "please enter a zip code" << endl;
  cin >> zip;
  while (zip != 5)
  {
	  if (zip == 5){
	  cout << "valid zip code" << endl;
	  }else {
	  cout << "non valid zip code" << endl;
	  }
  }
  system("pause");
  return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
int main ()
{
  string str;
  cout << "please enter a zip code" << endl;
  cin >> str;
  if (str.size() <= 5){
  cout << "valid zip code" << endl;
  }else {
  cout << "non valid zip code" << endl;
  }
 
  return 0;
}


You're having the user input set to one int, instead of the entire zipcode,
the easiest way is to have them enter in the zipcode as a string, then check to see if its size is greater than 5.
You are using a constructor that takes an integer as argument. Such a constructor doesn't exist (http://www.cplusplus.com/reference/string/string/string/).
What is the zip variable actually?
Checking the length of a string (while (zip != 5)) can be done using the size() (or length() ) function: str.size() returns the length of str (amount of characters in it, http://www.cplusplus.com/reference/string/string/size/ ).
Last edited on
One other problem I can see (though I could be wrong) is you have used parentheses instead of square brackets on line 9.

http://www.cplusplus.com/doc/tutorial/ntcs/
ok so I would doing this work
1
2
string str (zip) ;
  
No, you would just declare the string object itself. Why are you thinking you need to include parentheses in the string declaration?
You don't need to include any string length restriction on the input of 'str' because you evaluate 'str' later in the code for its validity anyway - this is what Scorpic and Raezzor are saying. Its unnecessary to have both methods of validation (i.e. your own 'IF' statement and string input length restriction)
Last edited on
Topic archived. No new replies allowed.