checking a string for a char

This is a discussion on checking a string for a char within the C++ Programming forums, part of the General Programming Boards category; basically, i'm asking for a number of strips, and so this has to be an integer. now what i have ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    24

    checking a string for a char

    basically, i'm asking for a number of strips, and so this has to be an integer.

    now what i have done is made it so that when u enter the number of strips, it saves it as a string in a file.

    then it reads the file, twice, storing the value as a float and an integer and then checking that when you take one away from the other, it equals 0. This checks the value entered is an integer.

    if you enter a character (first) it will again fail.

    BUT

    and this is my problem........ if i enter say 45h, it will work, using the number 45.

    i would like to be able to make it bring up an error if there is a character within the string.

    is this possible?

    Code:
    cout << "\nPlease input the number of strips required:  ";
            
    	cin >> q;
    
    	ofstream prt ("strips.dat");
    		prt << q << endl;
    		
    		ifstream read1 ("strips.dat");
    		read1 >> n1;
    		
    		ifstream read2 ("strips.dat");
    		read2 >> n2;			
    					
    		n3 = n2 - n1;
    
       while (!(n1) || n1 < 1 || n3 != 0 )         
    
                {
    		
                	cin.clear();
    	textcolor(12);
                	cprintf ("The number of strips must be a positive integer.");
                	cout << "\nPlease try again: ";
    
                	cin >> q;
    
                    ofstream prt ("strips.dat");
    	prt << q << endl;
    		
    	ifstream read1 ("strips.dat");
    	read1 >> n1;
    			
    	ifstream read2 ("strips.dat");
    	read2 >> n2;
    
    	n3 = n2 - n1;
    		
    	
    	    }

  2. #2
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161
    Use cin.getline() and test each character entered. If a non-digit is found, fail.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    24
    i have never used cin.getline before........ how would i go about using it?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    > i have never used cin.getline before........ how would i go about using it?
    Try to recall the name of the previous function you never used before, and how you went about finding out how to use it.
    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.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    IMO, there is an easier way than getline. I couldn't tell which part of the code you wanted to modify to check for the character. If it is the aprt where you read in q, then you can just check the next character in the stream. If it is a newline then everything is ok because the newline comes from when the user types the number then hits enter. You can use cin.get() != '\n' to find a bad character after the integer.

    If you are referring to the filestream, then you might consider using peek() instead of get() so that you don't accidentally read in the wrong thing.

    A common technique of reading in an int and only an int is this:
    Code:
    while (!(cin >> q) || cin.get() != '\n')
    {
      cin.clear();
      cin.ignore(1000, '\n'); // any big number will do
      cout << "Invalid response.\nPlease input the number of strips required:  ";
    }

  6. #6
    Registered User
    Join Date
    Mar 2006
    Posts
    24
    its when i input q that i want to check.

    ie.

    Code:
     cin >> q;
    
     check q for any chars, if so, then fail.
    thats basically what i am trying to do. i will keep at it though!! quite new to this, and so takes a while sometimes to figure out what's actually going on!!

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Ok, then I basically gave you the exact code that will do what you want. cin >> q returns false if the integer is not available, which causes the body of the while loop to be entered. If an integer is available, then cin.get() != '\n' checks to see if only an integer is entered by getting the next available character and checking it against a newline. If it isn't a newline, the body of the loop is entered. Inside the loop, the fail state of cin is cleared so you can try again. Then, any leftover characters in the input stream are ignored (or up to 1000 characters if the user actually typed that many). Finally, you tell the user that they input a bad response, and then ask them to try again. Control then goes back to the while loop that again tries to read in an integer like before.

  8. #8
    Registered User
    Join Date
    Mar 2006
    Posts
    24
    thank you VERY much!!

    have (i think sorted it. so much easier than what i was trying to do!! )

  9. #9
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161
    I find Daved's solution more complicated than getline and test.
    1) Using getline() by default clears the input stream -- no ignoring is necessary
    2) cin >> q relies on an error in processing

    Using cin.getline() then test each character entered is more straight forward IMO. And easier for the new programmer to understand.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    The problem is that in addition to using getline, you must also convert the string to an integer to use it. Doing so correctly can be cumbersome, while the cin >> code does it automatically.

    Also, checking for a character can get complicated. It might not be the case in this particular instance, but negative numbers or floating point numbers can have non-numeric characters but still be valid. The cin >> works well as is for those situations. I would use the getline method for more complicated parsing that doesn't have a built-in solution.

  11. #11
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161
    Converting the string to an integer is cumbersome?

    num = atoi(charstring); // if a char*
    num = atoi(string.c_str()); // if a string value

    What's the problem? And if you don't like those, there are many other options, some more cumbersome, some simple.
    Last edited by WaltP; 03-20-2006 at 08:53 PM.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    How do you tell the difference between "0" and "joe"? At that point it is already as cumbersome if not more so than using operator>>.

    ...

    Well, I guess if you already checked for characters then you wouldn't have to worry about it, so the cumbersome conversion argument was wrong. Perhaps a code example of using getline, looking for characters, and converting to an integer would convince me that it is easier to use and understand than taking advantage of operator>>.
    Last edited by Daved; 03-21-2006 at 12:31 AM.

  13. #13
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161
    Quote Originally Posted by Daved
    How do you tell the difference between "0" and "joe"? At that point it is already as cumbersome if not more so than using operator>>.

    ...

    Well, I guess if you already checked for characters then you wouldn't have to worry about it, so the cumbersome conversion argument was wrong. Perhaps a code example of using getline, looking for characters, and converting to an integer would convince me that it is easier to use and understand than taking advantage of operator>>.
    Try writing it and see. You can do it in under 10 lines from input to conversion.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  14. #14
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Code:
    int q;
    bool badData = true;
    while (badData)
    {
      cout << "Please input the number of strips required: "
      badData = false;
      char temptext[1000];
      if (!cin.getline(temptext, 1000, '\n'));
        badData = true;
      for (char* c = text; *c && !badData; ++c)
      {
        if (!isdigit(*c))
          badData = true;
      }
      if (badData)
        cout << "Invalid Response.";
      else
        q = atoi(temptext);
    }
    Perhaps a better code example would convince me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 03:45 PM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 12:57 PM

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