getCharacter()


Let me write the question out the way it is in the book. That may explain more what I am looking for:

Write the C++ code for a function that prompts the user to enter a character, and then stores the character in a char variable. The function should return the character entered by the user. the function will not have nay actual arguments passed to it. Name the function "getCharacter()."
Last edited on
Is the function that you need to WRITE called getCharacter()?

1
2
3
4
5
6
7
8
9
10
11
#include <conio.h>

char getCharacter();

int main() {
  char c=getCharacter();
}

char getCharacter() {
  return getche();
}
the above wont work...we are using Microsoft Visual Studio and he wont accept using #include <conio.h>
I tried the code without that and the code wont work...so I need something else
change this part of the previous code:
1
2
3
char getCharacter() {
  return getche();
}


to:

1
2
3
4
5
6
char getCharacter() {
  char c;
  c=cin.get();
  cin.ignore(256, '\n');
  return c;
}


You will need to press ENTER after you type your character. However, if someone types in more than one charater, the cin.ignore() function will kick it out of the input stream so it doesn't mess with your program later.
Last edited on
ok, where do I place the ''cout<<"Please enter a character from the keyboard==>\n\n"?
Anywhere in your program right before you call your getCharacter function.
For example:
1
2
3
4
5
int main() {
  char c;
  cout << "Enter a character -->";
  c=getCharacter();
}

Or, if you NEED to ask for the character from within your getCharacter() function itself, put that line right before the one that says: c=cin.get();
Topic archived. No new replies allowed.