Like Tree2Likes
  • 2 Post By Salem

Program seems right, but not executing properly in C++

This is a discussion on Program seems right, but not executing properly in C++ within the C++ Programming forums, part of the General Programming Boards category; Greetings masters of coding! I must begin by noting that I am fairly new to all of this, but I ...

  1. #1
    Registered User Techgique's Avatar
    Join Date
    Jun 2011
    Location
    San Diego
    Posts
    9

    Program seems right, but not executing properly in C++

    Greetings masters of coding!

    I must begin by noting that I am fairly new to all of this, but I learn quickly and appreciate any advice. I am in my second quarter of C/C++ programming and I ran into this little doozy.

    What seemed simple enough, I was tasked with writing a program that reads in state abbreviations and spits out the state names. No looping necessary, just a simple if, else if-type program.

    I am sure that there are many ways to write this little guy, but this even stumped my professor and together we couldn't find fault in the code. I ran it on visual studio 6 and bloodshed dev, but was receiving the same output.

    I even put it a cout to make sure that the characters (string) were reading into the declared variable and it was! However, the if statements were not working. I also took out the || (or) statement to simplify things and it still passes the entire run of if statements and simply prints the last else statement.

    I am not requesting a different way to write it, I was hoping for knowledge as to why this would not work. On a side not, I was getting that weird auto-close thing, but I assume that is a setting in bloodshed and simply put a system("PAUSE") in there to alleviate it.

    Here we go:
    Code:
    #include <iostream>
    // #include <string> I tried including this, but it didn't change things
    using namespace std;
    //State Abbreviations
    
    
    
    int main()
    {
    	const int SIZE = 3; //Setting the array size
    	char abb[SIZE];
    
    	//Get State abberviation
    	cout<<"Enter in your state abbreviation ---->";
    	cin>>abb;
    
    	//Begin if statement checking for the upper or lower case entry
    	if ((abb == "NC")||(abb == "nc"))
    		cout<< "Your state is North Carolina\n";
    	else if ((abb == "SC" ) || (abb == "sc"))
    		cout<< "Your state is South Carolina\n";
    	else if ((abb == "GA" ) || (abb == "ga"))
    		cout<< "Your state is Georgia\n";
    	else if ((abb == "FL" ) || (abb == "fl"))
    		cout<< "Your state is Florida\n";
    	else if ((abb == "AL" ) || (abb == "al"))
    		cout<< "Your state is Alabama\n";
    	else cout << "You have entered an incorrect value";
    	
    	system ("PAUSE");
    	return 0;
    }
    Many thanks for any help.

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,649
    You can't compare C-strings (which is what you're using when you should be using std::string) with ==. You must #include <cstring> and use strcmp(). If you use C++ std::strings you can use ==.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    You entire problem is your comparisons are incorrects. You are trying to compare an address with a string literal.

    Change your comparisons to
    [code]
    if ( strcmp(abb, "NC") != 1 || strcmp(abb, "nc") != 1 )
    std::cout << "Your state is North Carolina\n";
    [code]

    You could further increase the readability of the code by building a list that holds state abbreviations, and state names, then just loop through and do a comparison based on an index of your list.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    strcmp returns 0 on a match, or greater than zero, or less than zero depending on the order the two strings fall.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    C++ String Tutorial

    It's not a weird auto-closing thing by the way; the program is doing exactly what it should do upon completion. Weird auto-closing thing FAQ
    Last edited by AndrewHunter; 06-29-2011 at 06:40 PM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  6. #6
    Registered User Techgique's Avatar
    Join Date
    Jun 2011
    Location
    San Diego
    Posts
    9

    Wink

    Thank you everyone for your assistance! Couple things here. (This is my first couple weeks of C++ so I'm still scooting the C stuff aside and replacing it with the C++ language within the limitations of my fluency)

    I apologize, but I am not yet familiar with the std:: thing, but I will research that on my own when I get a sec.

    Rags, I will look into those differences as I build my knowledge base so I don't need to inquire about such elementary issues, ty.

    Raigne, thank you, as that got me on the proper track, but I couldn't get it to work in that fashion and ended up using ==0 for my comparisons, however, I did end up setting up that list just to try it out and it worked fantastically.

    Finally, Andrew, you picked up on my subtle begging to answer that closing window issue and after reading that article it makes sense and I shouldn't have that problem again, much appreciated.

    I look forward to getting to the point where I too can assist those in need rather than looking for answers. Thank you all and if anyone was interested, here is the working code.

    Code:
    int main()
    {
    	const int SIZE = 3; //Setting the array size
        char abb[SIZE];
    	const char north[SIZE] = "NC";
        const char northc[SIZE] = "nc";
        const char south[SIZE] = "SC";
        const char southc[SIZE] = "sc";
        const char Geo[SIZE] = "GA";
        const char Geor[SIZE] = "ga";
        const char Flo[SIZE] = "FL";
        const char Flor[SIZE] = "fl";
        const char Ala[SIZE] = "AL";
        const char Alab[SIZE] = "al";
        
    	//Get State abberviation
    	cout<<"Enter in your state abbreviation ---->";
    	cin>> abb;
        
    	//Begin if statement checking for the upper or lower case entry
    	if ( (strcmp(abb, north) == 0) || (strcmp(abb, northc) == 0) )
    		cout<< "Your state is North Carolina\n";
        else if ( (strcmp(abb, south) == 0) || (strcmp(abb, southc) == 0) )
    		cout<< "Your state is South Carolina\n";
    	else if ( (strcmp(abb, Geo) == 0) || (strcmp(abb, Geor) == 0) )
    		cout<< "Your state is Georgia\n";
    	else if ( (strcmp(abb, Flo) == 0) || (strcmp(abb, Flor) == 0) )
    		cout<< "Your state is Florida\n";
    	else if ( (strcmp(abb, Ala) == 0) || (strcmp(abb, Alab) == 0) )
    		cout<< "Your state is Alabama\n";
    	else cout << "You have entered an incorrect value";
    	
    	system ("PAUSE");
    	return 0;
    }

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Quote Originally Posted by Techgique View Post
    ...
    I apologize, but I am not yet familiar with the std:: thing, but I will research that on my own when I get a sec.
    It's a namespace and it is used quite often within C++. Namespace FAQ
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    I meant more like this by the list
    Code:
     #include<iostream>
    // #include <string> I tried including this, but it didn't change things
    usingnamespace std;
    //State Abbreviations
    #include<string>
    typedefstruct State
    {
    std::string Abbreviation;
    std::string StateName;
    } State;
    State states[50] = { { "NC", "North Carolina"},
    { "AR", "Arkansas" },
    { "So on", " and so on you go" },
    };
    bool Check(const std::string& Selection)
    {
    for ( int x = 0; x < 50; x++ )
    {
    if ( states[x].Abbreviation.compare(Selection) == 0 )
    {
    std::cout << "\nYour selection was: " << states[x].StateName << "\n";
    returntrue;
    }
    }
    returnfalse;
    }
    int main()
    {
    std::string abb;
    //Get State abberviation
    cout<<"Enter in your state abbreviation ---->";
    cin>>abb;
    if ( !Check(abb) )
    std::cout << "Failed to locate Abbreviation.\n";
    system ("PAUSE");
    return 0;
    } 
    
    I will leave it to you to google on how to ignore case in string comparisons.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    I don't know what you used to colourise your code, but my cat coughs up better formatted code than that!
    Ripping out random spaces so it won't compile is hardly a good thing.

    Perhaps press the "Go Advanced" button and preview your post before submitting?
    Elysia and iMalc like this.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    Your cat very well may, but Copy-Paste from VS2010Pro produces the garbage you see.

    edit: I am not sure why, but sometimes it copies the color from VS and not formatting, and other times it copies formatting and not color, but never both. I am not sure of the reason behind this. The problem arose once the forum was updated.
    Last edited by Raigne; 06-30-2011 at 05:30 PM.

  11. #11
    Registered User Alex1205's Avatar
    Join Date
    Jun 2011
    Location
    Ukraine
    Posts
    2
    Try this:

    Code:
    #include<iostream>
    #include<conio.h>
    using namespace std;
     
     
    int main()
    {
     
            char variants;
            cout<<" Please,enter your variant> \n";
     
            
            do{
                    cout<<" Variant 1 for North Caroline\n";
                    cout<<" Variant 2 for South Caroline\n";
                    cout<<" Variant 3 for Georgia\n";
                    cout<<" Variant 4 for Florida\n";
                    cout<<" Variant 5 for Alabama\n";
                    cout<<" Other symbol - exit\n";
                    cin>>variants;
     
      
                    switch(variants)
                    {
                            case'1'://if(str=="NC"||str=="nc")
                                            cout<<" Your state is North Caroline!\n";break;
                            case'2'://if(str=="SC"||str=="sc")
                                            cout<<" Your state is South Caroline!\n";break;
                            case'3'://if(str=="G"||str=="g")
                                            cout<<" Your state is Georgia!\n";break;
                            case'4'://if(str=="F"||str=="f")
                                            cout<<" Your state is Florida!\n";break;
                            case'5'://if(str=="A"||str=="a")
                                            cout<<" Your state is Alabama!\n";break;
                            default:cout<<" Good-bye!\n"; variants = '6'; break;;
                    }
       
            }while(variants != '6');
                    system("pause");
                    return 0;
     
    }

  12. #12
    Registered User Techgique's Avatar
    Join Date
    Jun 2011
    Location
    San Diego
    Posts
    9
    Thanks Alex, that was actually a different way that I had it working, but it was the if/else structure that my Professor insisted upon that was what was giving me problems.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Executing one program from within another...
    By Raigne in forum Windows Programming
    Replies: 2
    Last Post: 01-01-2007, 08:11 PM
  2. Replies: 40
    Last Post: 09-01-2006, 12:09 AM
  3. Executing a program
    By trancedeejay in forum C Programming
    Replies: 7
    Last Post: 03-06-2006, 07:55 AM
  4. Executing a program
    By trovoada in forum C Programming
    Replies: 15
    Last Post: 07-04-2005, 06:01 AM
  5. executing program....
    By Turek in forum Windows Programming
    Replies: 6
    Last Post: 08-01-2002, 02:13 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21