if else problems

I am new to c++ and I could use some help. I am working on a tax selection if/else statement;but it says that the st variable is currupted. anyone see what I am doing wrong? Or does anyone have a better way to have the module set the state tax rate?

int main()
{
char st[2];
float sTax;

cout<<"state?";
cin>>st;

if (strcmp (st,"GA"))
{
sTax=1.06;
}
else if (strcmp (st,"FL"))
{
sTax=1.04;
}
else if (strcmp(st,"SC"))
{
sTax=1.05;
}
else if (strcmp(st,"TN"))
{
sTax=1.06;
}
else if (strcmp(st,"AL"))
{
sTax=1.02;
}
else if (strcmp(st,"OT"))
{
sTax=1.00;
}
else
{
cout<<"error";
}
cout<<sTax;
return 0;
}
You haven't given st enough room to store the terminating null character. C-strings must have a zero as the last character (to indicate the end of the string).

However, since you are using C++, why not ditch C-strings in favor of std::string?

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
#include <algorithm>   // for the transform() function
#include <cctype>      // for the toupper() function
#include <functional>  // for the ptr_fun <> () adapter
#include <iostream>
#include <string>
using namespace std;

int main()
  {
  string st;
  float sTax;

  cout << "state? ";
  getline( cin, st );

  // this stuff makes sure the string is all uppercase
  transform( st.begin(), st.end(), st.begin(), ptr_fun <int,int> ( toupper ) );

  if      (st == "GA") sTax = 1.06;
  else if (st == "FL") sTax = 1.04;
  else if (st == "SC") sTax = 1.05;
  else cout << "error";

  cout << sTax;

  return 0;
  }

Hope this helps.
I'm sorry, this isn't really my strong point. It compiles and works for me but I think it may be because you're supposed to have a null character at the end of the array. i.e. /0. I don't know if that's automatic or what but try char st[3]

Something you may want to fix too, though this is up to you, is that you allow the user to enter past the end of the array. (into other parts of memory which may or may not be vital to the workings of your program) You don't want to allow that to happen so maybe think about a way you could prevent that.

Last edited on
Thank you both for responding. It works great.-- Now I just need to look into the other header files to see what all I can use them for.-- Class has only covered a few so far.
Heh, sorry. I use the STL a lot. You can forget <algorithm> and <functional> and just convert the string to uppercase yourself on line 17:
1
2
  for (unsigned n = 0; n < st.length(); n++)
    st[ n ] = toupper( st[ n ] );
Topic archived. No new replies allowed.