How to limit visible user input when using std::cin? - c++

I'm looking for a method to limit the visible user input using std::cin.
#include <iostream>
int main()
{
std::cout << "Enter your planet:\n";
string planet;
std::cin >> planet; // During the prompt, only "accept" x characters
}
What the user sees if they enter earth or any other word exceeding 4 characters before pressing enter:
Enter your planet:
eart
This is assuming the character limit is 4, note that the 'h' is missing. The console does not display any other character once it has exceeded the character limit. and this is before you press the enter key.
Kinda like typing in an input box like password fields, but it only allows 5 characters, so typing any other character goes unnoticed
A better analogy would be the maxlength attribute for text input in HTML.

That can't be achieved portably, because OS consoles aren't part of C++ standard. In windows, you could use <windows.h> header - it provides console handles etc., but since you didn't specify OS you are using, the is no point in posting windows-only code here (since it might not meet your needs).
EDIT:
Here is (not perfect) code that will limit visible input of the user:
#include <iostream>
#include <windows.h>
#include <conio.h>
int main()
{
COORD last_pos;
CONSOLE_SCREEN_BUFFER_INFO info;
std::string input;
int keystroke;
int max_input = 10;
int input_len = 0;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
std::cout << "Input (max 10) characters, press ENTER to prompt:" << std::endl;
GetConsoleScreenBufferInfo(handle, &info);
last_pos = info.dwCursorPosition;
while(true)
{
if(kbhit())
{
keystroke = _getch();
//declare what characters you allow in input (here: a-z, A-Z, 0-9, space)
if(std::isalnum(keystroke) || keystroke == ' ')
{
if(input_len + 1 > max_input)
continue;
++input_len;
std::cout << char(keystroke);
input += char(keystroke);
GetConsoleScreenBufferInfo(handle, &info);
last_pos = info.dwCursorPosition;
}
else if(keystroke == 8) //backspace
{
if(input_len - 1 >= 0)
{
--input_len;
input.pop_back();
COORD back_pos {short(last_pos.X-1), last_pos.Y};
SetConsoleCursorPosition(handle, back_pos);
std::cout << ' ';
SetConsoleCursorPosition(handle, back_pos);
GetConsoleScreenBufferInfo(handle, &info);
last_pos = info.dwCursorPosition;
}
}
else if(keystroke == 13) //enter
{
std::cout << std::endl;
break;
}
}
}
std::cout << "You entered: " << std::endl
<< input << std::endl;
}

After a few days of experimenting, I found another solution that seems to be quite easy to grasp as it is somewhat beginner level and without requiring any knowledge of windows programming.
NOTE:
The conio.h library function _getch() could easily be replaced with the getchar() function;
I'm not saying the previous answer was not okay, but this solution is sort of aimed towards beginners with only basic knowledge of c++
char ch;
string temp;
ch = _getch();
while(ch != 13)// Character representing enter
{
if(ch == '\b'){ //check for backspace character
if(temp.size() > 0) // check if string can still be reduced with pop_back() to avoid errors
{
cout << "\b \b"; //
temp.pop_back(); // remove last character
}
}
else if((temp.size() > 0) || !isalpha(ch))// checks for limit, in this case limit is one
{ //character and also optional checks if it is an alphabet
cout << '\a'; // for a really annoying sound that tells you know this is wrong
}else {
temp.push_back(ch); // pushing ch into temp
cout << ch; // display entered character on screen
}
ch = _getch();
}
This could probably use some tweaks, because it's definitely not perfect, but I think it is easy enough to understand, at least I hope so

Related

Does anyone have any idea how to make so the mask of the password is delayed by a second or two before it replace the password with '*'?

here is some fragment of my code. Can anyone help me? On how to make so the mask of the password is delayed by a second or two before it replaces the password with '*'?
struct adminInfo
{
string adminID;
string adminName;
string adminPassword;
};
void create_admin (adminInfo ad [], int &count)
{
char pass = 0;
const char BACKSPACE = 127;
const char RETURN = 10;
cout << " **************************************" << endl;
cout << " REGISTER ADMINISTRATOR" << endl;
cout << " **************************************" << endl;
cout << " Enter admin registration number (ID) : "; cin >> ws;
getline (cin, ad[count].adminID);
cout << " Enter admin full name : "; cin >> ws;
getline (cin, ad[count].adminName);
cout << " Please create your password : ";// cin >> ws;
//getline (cin, ad[count].adminPassword)
while ((pass=getch(void)) != RETURN)
{
if (pass == BACKSPACE)
{
if (ad[count].adminPassword.length() != 0)
{
cout << "\b \b";
ad[count].adminPassword.resize(ad[count].adminPassword.length() - 1);
}
}
else
{
ad[count].adminPassword += pass;
cout << "*";
}
}
count++;
}
Side note: Should std::endl always be used?
Also it might be easier for me to answer if I knew what libraries you were using. For the sake of simplicity I will presume you use the standard C++ library iostream for cout etc conio.h for getch() string for string and namespace std.
If you don't mind the last character being seen, you could literally just wait for the user input like this:
while ((pass = getch()) != RETURN) {
/* Making length variable so I don't have to call length() function multiple times and it looks cleaner */
int length = ad[count].adminPassword.length()
/* Using bigger than zero just to make it more explicit */
if (length > 0) {
/* Change last character to asterisk */
cout << "\b \b*";
}
if (pass == BACKSPACE) {
if (length > 0) {
cout << "\b \b";
ad[count].adminPassword.resize(length - 1);
}
} else {
ad[count].adminPassword += pass;
/* Instead of asterisk as that is now changed at every keypress after first input */
cout << pass;
}
}
If you wish to actually wait you could just include <windows.h> (or unix equivalent) and use Sleep(milliseconds) function like this in the else statement:
cout << pass;
ad[count].adminPassword += pass;
Sleep(Time in milliseconds)
cout << "\b \b*";
But this will wait the time in milliseconds to print out the next value and will give a pretty confusing and questionable output if you type above 3 wpm.
This is the best that I could think of, I'm not that knoweledgeable about C++ so sorry if I could not answer your question well enough.
I'm presuming you could do something with multithreading to make it wait while taking input. But as I said I do not know much about C++ so I will leave that to someone smarter than me ;D.

C++ Need some advices with Pig Latin string

I need to write a sentence in Pig Latin form and I am almost done it successfuly except for 1 case and I almost give up
for example :
If my word starts at a\e\o\u\i the word will look like easy -> easyway , apple -> appleway
and if it doesnt start with a letter that I wrote above
it will look like that: box -> oxbay , king -> ingkay
I succeed with the bolded part but in the first part with a\e\o\u\i letter at the beginning , I dont know where to put the w before and need some help with it
This is my code , thanks in advance
#include <iostream>
//Since those are used in ALL function of program, it wont hurt to set it to global
//Else it is considered EVIL to declare global variables
const int maxLine = 100;
char phraseLine[maxLine] = { '\0' };
void pigLatinString();
using namespace std;
void main()
{
// Displayed heading of program
cout << "* You will be prompted to enter a string of *" << endl;
cout << "* words. The string will be converted into *" << endl;
cout << "* Pig Latin and the results displayed. *" << endl;
cout << "* Enter as many strings as you would like. *" << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
cout << endl;
// This is the main loop. Continue executing until the user hits 'enter' to quit.
while (phraseLine[0] != '\0')
{
// Display the word (s) entered by the user
cout << "You entered the following: " << phraseLine << endl;
// Display the word (s) in Pig Latin
cout << "The same phrase in Pig latin is: ";
pigLatinString();
cout << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
}
return;
}
void pigLatinString() //phraseLine is a cstring for the word, maxline is max length of line
{ //variable declarations
char tempConsonant[10];
tempConsonant[0] = '\0';
int numberOfConsonants = 0;
char previousCharacter = ' ';
char currentCharacter = ' ';
bool isInWord = 0;
// for loop checking each index to the end of whatever is typed in
for (int i = 0; i < maxLine; i++)
{
//checking for the end of the phraseline
if (phraseLine[i] == '\0')
{//checking to see if it's in the word
if (isInWord)
{//checking to see that there wasn't a space ahead of the word and then sending the cstring + ay to the console
if (previousCharacter != ' ')
cout << tempConsonant << "ay" << endl;
}
return;
}
// this covers the end of the word condition
if (isInWord)
{// covers the condition of index [i] being the space at the end of the word
if (phraseLine[i] == ' ')
{
// spits out pig latin word, gets you out of the word, flushes the temp consonants array and resets the # of consonants to 0
cout << tempConsonant << "ay";
isInWord = 0;
tempConsonant[0] = '\0';
numberOfConsonants = 0;
}
cout << phraseLine[i] ;
}
else
{//this covers for the first vowel that makes the switch
if (phraseLine[i] != ' ')
{// sets the c string to what is in the phraseline at the time and makes it capitalized
char currentCharacter = phraseLine[i];
currentCharacter = toupper(currentCharacter);
// this takes care of the condition that currentCharacter is not a vowel
if ((currentCharacter != 'A') && (currentCharacter != 'E') &&
(currentCharacter != 'I') && (currentCharacter != 'O') && (currentCharacter != 'U'))
//this sets the array to temporarily hold the consonants for display before the 'ay'
{//this sets the null operator at the end of the c string and looks for the next consonant
tempConsonant[numberOfConsonants] = phraseLine[i];
tempConsonant[numberOfConsonants + 1] = '\0';
numberOfConsonants++;
}
else
{// this sets the boolean isInWord to true and displays the phraseline
isInWord = 1;
cout << phraseLine[i];
}
}
else
{
cout << phraseLine[i] ;
}
}
previousCharacter = phraseLine[i];
}
return;
}
You have two conditions to consider. if your word starts with a vowel, just add "way" to the end of the word, else move the first letter and add "ay" to the end.
This is a task that can be made a lot simpler by using std::string instead of C-strings. This is because you are now no longer concerned with exceeding your length or losing the null character. It also allows easier access to the Standard Library algorithms.
#include <algorithm>
#include <iostream>
#include <string>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiou");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::cout << make_pig_latin("apple") << '\n'
<< make_pig_latin("box") << '\n'
<< make_pig_latin("king") << '\n'
<< make_pig_latin("easy") << '\n';
}
The function above highlights how you can go about structuring your conversion. You just need to know if your word starts with a vowel or not, and take the appropriate action.
Output:
appleway
oxbay
ingkay
easyway
I did not get the impression that you have to care about words like 'phone'.
Looking through your code, you should try to do a better job at separating your concerns. Pig Latin is easier done one word at a time, but you have string splitting code and a lot of "not Pig Latin" code in your Pig Latin function. Your main can handle getting input. You should probably have a separate function to break the line up into individual words, using std::vector to hold the words would be best since it can grow on demand and doesn't have to know a specific capacity up front. You then iterate through your array of words and translate them individually. Depending on what your actual requirements are, it's possible that you don't even have to store the translated words, just print them directly to the screen.
Here's the same program, but now it can separate words. Note how the pig latin function doesn't have to change (much, I added upper-case vowels just because I didn't want to bothered converting words) in order for the added functionality to be added.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiouAEIOU");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::string phrase(
"A sentence where I say words like apple box easy king and ignore "
"punctuation");
std::istringstream sin(phrase);
std::vector<std::string> words(std::istream_iterator<std::string>(sin), {});
for (auto i : words) {
std::cout << make_pig_latin(i) << ' ';
}
}
Output:
Away entencesay hereway Iway aysay ordsway ikelay appleway oxbay easyway ingkay andway ignoreway unctuationpay

Code gets stuck in loop (but loop itself doesn't keep going). C++ string

I am currently self-studying C++ with Schaum's outline book (which covers mostly C contents, or so I've been told, but whatever) and I have encountered some trouble with problem 9.8.
You are supposed to count the number of appearances of every different word in a given c++ string, for which I assumed each word was separated from the next one by a white space, a newline or a dot or coma (followed in these two last cases by another white space).
My code is the following:
#include <iostream>
#include <string>
using namespace std;
int main()
{ string s;
cout << "Enter text (enter \"$\" to stop input):\n";
getline(cin,s,'$');
string s2 = s, word;
int ini = 0, last, count_word = 0;
int count_1 = 0, count_2 = 0, count_3 = 0;
cout << "\nThe words found in the text, with its frequencies, are the following:\n";
for (ini; ini < s.length(); )
{ // we look for the next word in the string (at the end of each iteration
// ini is incremented in a quantity previous_word.length()
last = ini;
cout << "1: " << ++count_1 << endl;
while(true)
{ if (s[last] == ' ') break;
if (s[last] == '\n') break;
if (s[last] == ',') break;
if (s[last] == '.') break;
if (last > s.length()-1 ) break;
++last;
cout << "2: " << ++count_2 << endl;
}
--last; // last gives the position within s of the last letter of the current word
// now me create the word itself
word = s.substr(ini,last-ini+1); //because last-ini is word.length()-1
int found = s2.find(word);
while( found != s2.length() ) // the loop goes at least once
++count_word;
s2.erase(0,found+word.length()); // we erase the part of s2 where we have already looked
found = s2.find(word);
cout << "3: " << ++count_3 << endl;
cout << "\t["<<word<<"]: " << count_word;
++last;
s2 = s;
s2.erase(0,ini + word.length()); // we do this so that in the next iteration we don't look for
// the new word where we know it won't be.
if (s[last] == ' ' || s[last] == '\n') ini = last + 1;
if (s[last] == ',' || s[last] == '.') ini = last + 2;
count_word = 0;
}
}
When I ran the program nothing was sshown on screen, so I figured out that one of the loops must had been stuck (that is why I defined the variables count_1,2 and 3, to know if this was so).
However, after correctly counting the number of iterations for the fist word to be found, nothing else is printed and all I see is the command prompt (I mean the tiny white bar) and I cannot even stop the program by using ctrl z.
This is a very complicated method for a very simple problem. You can just use a stringstream to extract each word seperated by a white space. You then just take the extracted word and increment the word counter using a std::map<std::string, int>.
My take on this:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main() {
std::map<std::string, int> word_to_count;
std::string in;
std::getline(std::cin, in);
std::stringstream s(in);
std::string temp_word;
while (s >> temp_word) {
word_to_count[temp_word]++;
}
for (const auto& x : word_to_count) {
std::cout << x.first << ": " << x.second << std::endl;
}
return 0;
}
input
hello world hello world test
Output
hello: 2
test: 1
world: 2
Keep in mind this is just one of many possible solutions, so just take this as inspiration :).

Input validation to filter out chars, strings, and a range of ints

I have looked in several places on the Internet but cannot find what I am looking for. Basically I am trying to understand data validation and filter out all user input except either the number 1 or 2. I have found information for validating ints. Found stuff on filtering out chars and strings. But when I try to put them together it doesn't work. Basically if the user enters something that is not 1 or 2, it does not end a loop asking for correct input.
I have included more details in the comments in the code below.
Any help is appreciated!
#include <iostream>
#include <string>
int main()
{
std::cout << "Please enter 1 or 2. No other numbers or characters."
<< std::endl;
std::string numberString;
//Used a string so if the user enters a char it gets converted to an
//integer value of 0.
getline(std::cin, numberString);
int numberInteger = atoi(numberString.c_str());
//If the user enters the wrong number, char, or string,
//the program goes to this area of code.
//But if a subsequent correct entry is made, the loop does not end.
if (numberInteger < 1 || numberInteger > 2)
{
do
{
//Tried using these two lines of code to clear the input buffer,
//but it doesn't seem to work either:
//std::cin.clear();
//std::cin.ignore(std::numeric_limits <std::streamsize>::max(), '\n');
std::cout << "Invalid input. Please enter 1 or 2. No other numbers or characters."
<< std::endl;
getline(std::cin, numberString);
int numberInteger = atoi(numberString.c_str());
} while (numberInteger < 1 || numberInteger > 2);
}
else
{
std::cout << "You entered either 1 or 2. Great job! "
<< std::endl;
}
return 0;
}
#include <cctype>
#include <limits>
#include <iostream>
std::istream& eat_whitespace(std::istream& is)
{
int ch;
while ((ch = is.peek()) != EOF && ch != '\n' &&
std::isspace(static_cast<char unsigned>(ch))) // 0)
is.get(); // As long as the next character
// is a space, get and discard it.
return is;
}
int main()
{
int choice;
while (std::cout << "Please enter 1 or 2. No other numbers or characters: ",
!(std::cin >> std::skipws >> choice >> eat_whitespace) || // 1)
std::cin.peek() != '\n' || // 2)
choice < 1 || 2 < choice) { // 3)
std::cerr << "I said 1 or 2 ... nothing else ... grrr!\n\n";
std::cin.clear(); // 4)
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 5)
}
std::cout << "Input was " << choice << '\n';
}
0) Don't feed isspace() negative values.
1) Extraction of an int failed. Allow whitespace before and after the int.
2) If the next character in the stream is not a newline character, there is garbage left eat_whitespace() didn't swallow --> complain.
3) choice not in range.
4) clear flags to make sure input functions will work again.
5) ignore up to maximum streamsize characters untill the next newline.

How to read from keyboard a complete random text, filter and cast

I`m developing a Tic Tac Toe game for school, but it is getting difficult develop a nice way to read a play from keyboard, in a practical and nice formated way.
This is what I did:
Human::play() const
{
int pos
std::cout << endl << Name << ", please, insert the desirable move:";
//^^this is a class atribute
std::string keyboard;
std::stringstream ss;
std::getline(std::cin, keyboard);
ss << keyboard[0];
ss >> pos;
return (pos);
}//end of Human class method *play*
This function will be called and I will verify if the player move was acceptable, thus, see if it is between 0 and 8. Also, I would like to check if there was an entry of "r" or "q", as it will mean that the player wants to come back one turn or quit the game.
To check if the player had enter this instructions, I do this i.e:
int playermove = player1.play()
if (playermove == 'q')
...
I am having troubles because from what was shown above, pos is returned 0 when a character is entered. But, I don't see any practical solutions.
Could you please suggest me alternatives?
You can check for r and q and on false just subtract -48 (because of ASCII table).
Check this out:
#include <iostream>
using namespace std;
int main() {
char tmp;
cin >> tmp;
if(tmp == 'q') {
cout << tmp;
return 0;
} else {
int smth = tmp;
cout << smth - 48;
return 0;
}
return 0;
}
This will catch q and numbers. You can then check if (smth - 48) is in range 0-9 by checking (> -48 && < -39).