scanf problems with strings and chars

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Noodles
    New Member
    • Sep 2011
    • 9

    scanf problems with strings and chars

    Hi,

    Im quite new to C++ and am trying to learn most of the commands.
    So i wanted to make a Programm that has a normal mode and a non normal mode, kindof.
    And i wanted to make a question, which the user has to answer to start normal or unnormal mode.
    I think this code should show my idea.

    The if command never Reacts to a j.
    Why is that??

    Code:
      char jon;
      
        printf("Should normal mode be executed?  [j/n]");
        cout << endl;
        scanf("%s",jon);
        fflush(stdin);
      if (jon == "j"){}
      else{}
    Thanks
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Line 3 and 4, do not mix C and C++ io routines, you have no guarantee they are compatible. You are using C++ so use C++ cout << "Should normal mode be executed? [j/n]" << endl;

    Line 5 This is C++ you should use cin not scanf. %s is for a C style string in an array of char but you provide a single char and not even a pointer to it.

    Line 6 Never ever flush stdin. It is undefined behaviour.

    Line 7 You can't do with a C style string in an array of char, you can do it with a single char but then you compare to a string constant which wont work. You can do this with a C++ std::string. You are using C++ do things the C++ way.

    Code:
    #include <iostream>
    #include <string>
    
      char jon;
      std::string stuff;
    
      std::cout << "Should normal mode be executed?  [j/n]" << std::endl; 
      std::cin >> jon;
      std::getline(cin, stuff); // Clear rest of line from stdin
    
      if (jon == 'j' || jon == 'J')
      {
      }
      else
      {
      }

    Comment

    • Noodles
      New Member
      • Sep 2011
      • 9

      #3
      Ohh,

      Ok thanks i didn't know the command cin, this makes life a lot easier.
      So thanks a lot!!!

      Comment

      Working...