how to take integers out of a scrambled text?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • trea
    New Member
    • Jul 2010
    • 1

    how to take integers out of a scrambled text?

    so I have this c++ homework which wants me to take a text input like "north6east7wes t8"(the string follows the "direction+inte ger order) and have an input check. if the text does not have any integers it ought to give a warning message.

    and in another function I should take the integers out of the text (which I have no idea how to do) and convert them with atoi (which I could do).

    I hope I explained it clearly. Thanks in advance.
  • tetrahedral
    New Member
    • Jul 2010
    • 7

    #2
    Originally posted by trea
    so I have this c++ homework which wants me to take a text input like "north6east7wes t8"(the string follows the "direction+inte ger order) and have an input check. if the text does not have any integers it ought to give a warning message.

    and in another function I should take the integers out of the text (which I have no idea how to do) and convert them with atoi (which I could do).

    I hope I explained it clearly. Thanks in advance.
    So what exactly is your question?

    Also, please see the FAQ about asking for homework solutions.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Consider using the >> operator.

      Code:
      cin >> data;
      and data is a char, you have fetched one character. If data is not a char, then the >> operator fails.

      So you might try:

      Code:
      cin >> anInt;
      
      If this fails then the data is not an integer, try again using a char
      
      cin >> aChar;
      Wrap this in a loop an off you go.


      Note that an input of 1234x and you perform cin>>anInt will place the value 1234 in anInt. That is, you do not use atoi or atoanythingelse in C++.

      Comment

      • whodgson
        Contributor
        • Jan 2007
        • 542

        #4
        Another way maybe to get the length of the string 's' with s.length()run through your string within a for loop,using < s.length() as the end condition, and identify the integers with something like if(s[i] >= '0' && s[i]<='9') and increment count++ so that you can print out the number of integers. Can you guarantee there will be only one character in each integer? If not you will need to check if s[i-1] is or is not also an integer.
        Alternatively if s[i] is >='a' && <='z' you could could replace 'a' --> 'z' with " " which would leave only the integers.

        Comment

        Working...