![]() |
Okay I am learning C++ using the book: Teach Yourself C++ third Edition.
I am trying to write a simple program, that asks the user for some text then, out puts that text as well as the count of characters used. My program is using cin.get() I need to use this so I can see the result of my program and make sure it is working correctly, but I can't seem to get cin.get() working. here is the code: /* A C++ program that uses I/O to prompt user for a striong and then display its length */ #include <iostream> #include <string> // library that allows the use of cin.get(); (stops the program) I think using namespace std; int main() { char i; double d; cout << "Please enter some text."; cin >> i; cout << i; cin.get(); return 0; } |
:
#include <iostream> |
>but I can't seem to get cin.get() working
It's best to assume that any use of cin>> [something] will leave a newline character in the stream. cin.get() isn't working because it finds a newline (which it terminates on) and finishes immediately without giving the user a chance to type anything. You'll find a similar problem, along with suitable solutions, here. >getch(); getch should be avoided when there is a reasonable alternative that is also portable and standard. |
Is there a portable equivalent of getch() - a function that retuns a single character and doesn't echo?
|
No, terminal operations are highly platform-dependent. Though it's generally a trivial task to simulate the functionality on a system that doesn't provide getch through a system API.
|
Ah, well... worth a shot. Though it's a bit surprising there isn't something in std::cin.
|
>Though it's a bit surprising there isn't something in std::cin.
Not when you consider that the standard input stream isn't necessarily a terminal. For example, how would getch work if the standard input stream were redirected to a file? The problem with getch is somewhat related to the screen clearing problem. How do you clear the screen? Well, how do you define a screen? How do you get everyone to use the same definition of a screen? What if the system doesn't have a screen? The standards body needed to take all of this into account since C++ is supposedly a "portable" programming language |
Fair enough :P
|
| All times are GMT -5. The time now is 2:06 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC