c++ string.compare don't accept space characters - c++

First I want to apologist about my bad title. Now the problem. I'm trying to compare two strings in C++. I had try with string.compare and ==, none of them worked. Here is code
if(game_type == "AI vs AI"){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
and with string.compare
if(game_type.compare("AI vs AI") == 0){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
If I give AIvsAI for input the program works correctly, but if i enter AI (space) vs (space) AI, the program prints "Error". I tried using \x20 instant of space but this didn't work too. Any ideas why this is happening?

It appears that you are using a statement similar to
std::cin >> game_type;
to obtain the user input. The problem is that the >> operator only extracts the first word from the line the user types, which makes game_type only contain AI when you type AI vs AI. (As a side note, if you were to use std::cin >> blah on the next line, then blah would contain vs because that typed input had not been consumed yet.)
To fix this, you can use std::getline:
std::getline(std::cin, game_type);
This gets everything the user types on the line (up to but not including the Enter keypress) and puts that in game_type. This is almost always the right way to get user input for an interactive program.

Related

White space on the end of output string not printing with the string, but rather with the next printed line after it

I tried to print a line that asks for input from the user, get the input, then print again some line. The problem is that the white space at the end of the first printed line is printed not at the end of the line, but rather at the beginning of second printed line, after i get the input.
I'm completely new to C++ so I couldn't really try much, but i tried printing the code without the part that prompts the input from the user, and it prints the space just fine, but when i add std::cin << input; the space get's sent to the beginning of the second line.
My code:
int input;
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> input;
std::cout << "Amazing... That's my favorite number too... wow..." << std::endl;
I want the output to be
Enter your favorite number between 1 and 100: //some input
Amazing... That's my favorite number too... wow...
(note the space before //some input)
Instead i get
Enter your favorite number between 1 and 100://some input
Amazing... That's my favorite number too... wow...
(note the space before Amazing)
Edit: I'm using Clion if it could be connected. Also, I tried to run the executable on powershell and it worked as expected, without the problem, so this has something to do with the Clion terminal. Also, i'm using windows 10 as my OS.
Second Edit: add my findings on my answer.
This seems to be a problem with buffered input of Clion. See this issue: https://youtrack.jetbrains.com/issue/CPP-7437
When you are using CLion, You can try disabling PTY (Help | Find Action > type "Registry" > open Registry > find and disable the run.processes.with.pty option)
CLion moving space into new line
Are you sure about that? I tried both in online shell and on local machine and it works as expected.
After checking I found out that this occurs only on the Clion Run terminal, so this has something to do with it exclusively. I'm currently trying to mess around with the settings. I will post a solution and an explanation here if I find it.
Edit: as mentioned in one comment, it could be the issue mentioned here https://youtrack.jetbrains.com/issue/CPP-7437.
In any case it is a Clion related problem exclusively, and not a C++ problem.
This problem is only applicable for the second line, if you leave that line empty then the problem will be fixed. Don't know about C++ but for C before the print statement you have to add: printf("\n");

C++: Flawed console output on using a conditional statement

I'm a newbie to C++ (and to programming in general). I wrote a program that reads and writes staff contact details. This code works well:
// appropriate headers...
int main()
{
char trigger{};
int options = 0;
bool testing{};
fileIps Inptbox; // for entering new data
char ext_title[20]; char ext_intercomNum[4]; char ext_dept[20];
printf("%s", "Enter Officer's Title:\n");
gets_s(ext_title, 20);
printf("%s", "Enter Officer's Intercom Number:\n");
gets_s(ext_intercomNum, 4);
printf("%s", "Enter Officer's Department:\n");
gets_s(ext_dept, 20);
Inptbox.rcv_values(ext_title, ext_intercomNum, ext_dept);
Inptbox.create_string();
testing = Inptbox.validate();
if (testing == true)
return -1;
else if (testing == false)
Inptbox.write_string();
// more code below...
My question is regarding the console output. I had tried to introduce conditional statements to enable selecting a read or write mode. The above code is for writing to file. There are more lines of code below for reading from file and they, too, worked okay.
My challenge is that once I introduce a conditional statement for the above code...
printf("%s", "Enter 1 to WRITE DATA or 2 to READ DATA\n");
cin >> options;
if (options == 1)
{
fileIps Inptbox; // for entering new data
//... rest of code...
}
// more code below...
...the output on the console is flawed, as the prompt for the first entry is displayed but is totally skipped, forcing the user to enter 'Officer's Intercom Number' first. The third prompt worked well.
To elaborate further, when I used cin to assign the value 1 to options (i.e. applying the condition), the console would immediately print...
Enter Officer's Title:
Enter Officer's Intercom Number:
...making it impossible for me to fill in the first entry (i.e. 'Title').
I struggled with this and tried several things to fix it. I used fgets() and even tried it with gets(). I revisited my classes, yet nothing worked. I read widely on things like buffering, studied questions on this site and looked through various resources on cstdio as well as ios_base and its derived classes (which was good because I learned a bunch of other things). However, unless I removed that 'if' statement from my code, nothing I else I tried worked.
So, my question is: "How can this kind of behaviour be explained and how best could I implement my code to enable me toggle between read and write mode?"
I am working with MS Visual Studio 2015.
Using the formatted extraction operator '>>' has its problems. In this case, it reads all values that can convert to an integer. However, you must give an enter to signal that you're ready. The >> operator does not process that newline. When the next time input is read, it sees the previously given newline character. Hence the 'Enter Officer's title' input is immediately set to a newline and continues. Try using something like:
std::string line;
getline(cin, line);
And test the string or convert it.

erasing the last value from the std::cout

I am creating a guessing game for two players. I first want a user to enter a number, which is intended to be secret. In order to keep it secret, I want to erase whatever the user has entered to cin last. I am trying to move the cursor back and insert a blank space where the user has entered a number. I am attempting to use cout << "\b" << "\b" << "\b" << " " as of right now, which you can see in my loop below.
here is my code so far:
do{ //initial do-while loop to begin game
int secretNumber = 0; //initilized to a default value of 0 to make the compiler happy
do {
//prompt user for input
cout << "Please choose a secret number between 1 and 10: ";
//read in user input
cin >> secretNumber; //store user input in variable
cout << "\b" << "\b" << "\b" << " "; //<------- this is my attempt to clear the user input
if(secretNumber <= 0 || secretNumber > 10){
cout << "You have attempted to enter a number outside of the acceptable range." << endl;
}
}while ((secretNumber <= 0 || secretNumber > 10)); //repeat do-while loop if user input is out of range
Currently this just prints another line, with a space as the first character, instead of going back to the previous line and replacing the user inputted integer with a " ".
Please do not give me any OS specific solutions, I need this to compile on both windows and linux.
If your terminal emulator (or the command shell you use on Windows) supports basic ANSI control characters, you could output a reverse line feed sequence followed by a kill line sequence. The reverse line feed is necessary because the user will have typed a carriage return in order to terminate the input, so the cursor is no longer on the same line. Those codes are "\033[F" and "\033[K", respectively. But there is no guarantee that this will work.
Historically, you could use the now-withdrawn Posix interface getpass to read a line without echoing. I don't believe that was implemented by Windows, and while it is still part of glibc, its use is discouraged. Unfortunately, there is no standard replacement.
Console-independent terminal control is available in Posix systems using the termios facilities; basically, you just need to turn off the ECHO flag. (See man termios for more details.) On Windows, there is a similar interface. However, it is very easy to get into trouble with these interfaces because you need to re-enable echoing even if the user kills the program with ctl-C (or suspends it with ctl-Z). Getting that right is tricky, and the naive solutions you'll find floating around on the internet typically don't.
Having said that, see Getting a password in C without using getpass (3)? for some possible solutions.

Problems looping in C++ with \n

What I am trying to do is make a while loop that loops as long as "\n" is not entered. The problem is that it asks for my input once and then just ends. Here is my code
paliTester = cin.get();
while (paliTester != "\n")
{
paliTester = cin.get();
}
The problem is not with your code, the problem is with the console that is providing you with your input. All consoles today provide a line editing option. Meaning you can type a command, erase part of it and rewrite as many times as you want. Until you'll press ENTER no input will be provided to the program waiting to read it. This means there's no way to provide any content to your program without pressing ENTER and ENTER means your program will receive '\n'.
Probably because \n is the new line escape sequence. Use "\\n" instead.
Also try this instead of get().
cin >> paliTester;
while (paliTester != "\\n")
{
cin >> paliTester;
}

Trying to Read a Line of Keyboard Input in C++

I mam trying to complete a college assignment in C++ and am having trouble with what should be a very basic operation. I am trying to read a string of characters from the keyboard. This is the relevant code:
string t;
cout << endl << "Enter title to search for: ";
getline(cin, t, '\n');
I understand, that the last line is supposed to read the input buffer (cin , in this instance) and store the character in the 't' string until it reaches a new line character and then continue the program flow.
However, when I run my code in XCode, it just sort of jumps over the getline function and treats 't' as an empty string.
What's going on? I tried using cin >> t but that just read characters forever - Why cant I get this to behave?
The reason that the input operation apparently is skipped, is most probably (that means, ignoring possible peculiarities of a bugsy XCode IDE) that you have performed some input earlier and left a newline in the input buffer.
To fix that, make sure that you have emptied the input buffer after each input operation that logically should consume a line of input.
One easy way is to always use getline into a string, and then use e.g. an istringstream if you want to convert a number specification to number type.
Cheers & hth.,
From the docs page it looks like you want
cin.getline(t,256,'\n');
or something similar.
This sounds like an issue with the way Xcode is running your program. Try running your program directly from the terminal, and see if this is sufficient to fix your issue.