I am trying to find a way to have the input stop without the need to press Enter when user inputs the delimiting character in getline function in my practice application.
Currently the input stream from getline is only interrupted if user presses Enter after typing in delimiting character and the cout message explains it to the user but preferably I would prefer for input to simply stop when delimiter is pressed.
Looking for suggestions on how I could stop the input when it detects a specified character.
Here is full code I have :
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#define DEBUG 1 // 1 = enabled
int main()
{
char takeFirstNonSpaceCharacter(string text);
string message;
char stopper;
string stopperInput;
cout << "Type the character with which you want to signal end of a message\n";
cin >> stopperInput;
cin.ignore(128, '\n'); //clean cin
stopper = takeFirstNonSpaceCharacter(stopperInput); //in case input has white spaces
cout << "Type your message, make it as long as you want.\n To finish typing enter the " << stopper << " symbol followed by Enter\n Input after the " << stopper << " symbol will be lost\n";
getline(cin, message, stopper);
#if DEBUG == 1
cout << message << '\n';
#endif
system("pause");
return 0;
}
char takeFirstNonSpaceCharacter(string text)
{
string::const_iterator iter = text.begin();
while (iter != text.end())
{
if (*iter != 32 || *iter != 10 || *iter != 9) //ascii: 32 = space, 10 = new line, 9 = horizontal tab
{
return *iter; //if its not space character then it must be a character (unless the user can somehow type for example \0 on keyboard)
}
else
{
iter++; //if its space
}
}
return '\0';
}
With the input/output being around this (bold is my input)
Type the character with which you want to signal end of a message
}
Type your message, make it as long as you want. To finish typing enter the } symbol followed by Enter Input after the } symbol will be lost
asdf}asdf
asdf