Thread: Stream question

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Stream question

    I'm trying to make a program which reads in a digit and then a character, if there is no digit then it puts a 1 into cin so the 1 will be read as the digit. When I input "1a" I get the correct output but when I input "a" I get "a" as the digit and the character. What am I doing wrong?
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	cout << "start\n";
    	char c;
    	cin.get(c);
    	if (!isdigit(c)) {
    		cin.putback(c);
    		cin.putback('1');
    	} else {
    		cin.putback(c);
    	}
    
    	cin.get(c);
    	cout << "digit " << c << '\n';
    	cin.get(c);
    	cout << "letter " << c << '\n';
    }

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    From
    http://www.cppreference.com/cppio/putback.html:

    The putback() function is used with input streams, and returns the previously-read character ch to the input stream.
    The "previously-read" character, not any character you choose. Anyway, why are you trying to push a character onto the input stream? Why not just print your default digit if a digit is not read from cin?

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    would probably be easier to read the whole thing into a string and go from there
    Code:
    string s;
    cin >> s;
    if (!isdigit(s.at(i))) {
         cout << 1;
    }
    cout << s << endl;

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    cin >> s;
    does not reads the whole string - only upto the first whitespace
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    only upto the first whitespace
    That is what I meant by the "whole string" not the "whole line".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stream Factory Interface (Question of Preference)
    By phantomotap in forum C++ Programming
    Replies: 7
    Last Post: 05-02-2008, 03:43 PM
  2. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  3. Stream function question
    By 3kgt in forum C++ Programming
    Replies: 1
    Last Post: 03-04-2003, 06:30 PM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. fscanf() question
    By Encrypted in forum C Programming
    Replies: 6
    Last Post: 01-20-2003, 01:14 PM