C++ String Input as if/else statement condition - c++

I saw a similar question to mine: C++ string variables with if statements
The only difference between his situation and mine is that I would like the condition to be if a string with a space is matching a certain string.
Here is my code:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string input1;
cout << "Welcome to AgentOS V230.20043." << endl;
cout << "To log in, please type \"log in\"" << endl;
cin >> input1;
if (input1 == "log in")
{
cout << "Please enter your Agent ID." << endl;
}
return 0;
}
For some reason, the if statement is not picking up the string. However, if the conditions is:
if (input1 == "login"
It works. I cannot find a way to use a string with a space in it with a condition. I am wondering if maybe the if statement is okay but that the cin is deleting the space.
Thank you!

You should use standard function std::getline instead of the operator >>
For example
if ( std::getline( std::cin, input1 ) && input1 == "log in" )
{
std::cout << "Please enter your Agent ID." << std::endl;
}

cin >> ignores whitespace, use getline:
getline(cin, input1);

You need to read the entire line with spaces with std::getline, it will stop when finds a newline \n or N-1 characters. So, just do the reading like this:
cin.getline( input1, N );
Where N is the max number of character that will read.

Related

How To Stop C++ From Repeating Itself? [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
How to read a file line by line or a whole text file at once?
(9 answers)
Closed 1 year ago.
Sorry for the poor question but I really do not know what is happening.
while (true) {
string choice;
cout << ">>> ";
cin >> choice;
if (choice == "hi") {
cout << "Whats up?" << endl;
} else {
cout << "error" << endl;
}
}
If I compile this and then input "hi" it will show
>>> hi
Whats up?
>>>
but if I do "hi hi"
>>> hi hi
Whats up?
>>> Whats up?
>>>
It will show that. Why is it showing Whats up? twice instead of the error message?
The problem is that std::cin is used to read either a number that is compatible with the type of the variable, or a single word at a time.
Technically, you're using formatted input operator>> which discards leading whitespace and will also stop reading when it encounters a whitespace/invalid input.
To solve this, replace cin >> choice; with:
std::getline(cin, choice);
This will read until '\n' is encountered, and now we're using unformatted input.
So, the modified code looks like:
while (true) {
string choice;
cout << ">>> ";
std::getline(cin, choice);//i modified this
if (choice == "hi") {
cout << "Whats up?" << endl;
} else {
cout << "error" << endl;
}
}
You can try out the code here.
As soon as std::cin reads a space character (this ' '), it won't consider any more characters that come after that space char as part of the input. So the next time it reads the buffer it will read the second "hi" and insert it to choice. It is like you're entering "hi" and pressing enter key and then doing it again. You will see "Whats up?" being printed twice.
Use std::getline(std::cin, choice); to get the full input even if there are space or tab characters in between the other characters.
If you want something more error-safe then this function might be helpful:
#include <iostream>
#include <limits>
void getCharInput( char arr[], const std::streamsize streamSize )
{
std::cin.putback( '\n' );
std::cin.clear( );
std::cin.ignore( std::numeric_limits<std::streamsize>::max( ), '\n' );
std::cin.getline( arr, streamSize );
}
int main()
{
constexpr std::streamsize streamSize { 11 }; // 11 as an example ( 10 for actual chars plus 1 for '\0' )
char inputBuffer[ streamSize ] { };
getCharInput( inputBuffer, streamSize );
std::cout << "Input is: <" << inputBuffer << ">" << '\n';
}
Only 11 chars (including the null-terminator '\0') will be read and stored in inputBuffer.

How to make string variables more than one word c++?

When I am trying to store more than one word in a string variable, it only outputs one word when I tell the program to print it. This is an example:
#include <iostream>
using namespace std;
string i;
int main() {
cout << "Input more than one word." << endl;
//in this case the user will input whats up//
cin >> i;
cout << i << endl;
//the program outputs 'whats'//
}
Instead of using cin >> i, use getline(cin, i).
The difference is that, with getline() you get all the words in a line, whereas with operator>> you get only one word at a time.
Replace that:
cin >> i;
for:
getline(cin, i);
and it will work :)

C++ User defined string needs to contain spaces (but not allowed by program..?)

I'm working on homework for my c++ class, and it's been quite awhile since I've used it. I was wondering if there was a way to allow spaces in a string (instead of it nulling out and ending the string)
my current code is this:
int chapter10() {
string strinput;
char charstr[1000];
int numwords=1;
cout << "Enter a phrase ";
cin >> strinput;
cout << strinput;
const int size = strinput.size() + 1;
strcpy_s(charstr, strinput.c_str());
cout << strinput << endl;
for (int i = 0; i != size; i++) {
if (*(charstr + i) == ' ')
numwords++;
}
cout << "There are " << numwords << " words in that string." << endl;
return 0;
}
The problem I'm having, is for instance, if I type "Hello World" and press enter, it pops the next line (right after the cin) and says "Hello", and the space made it cut the rest of the phrase off.
How does one fix this issue? I don't want to use the str:: things as I barely know what they are, and have really never had to use them, and that would look a bit suspicious to the teacher :P
Update: If you've suggested using getline(cin, strinput); It doesn't work too well. I can from what I see, only type in the 10 to reach my function, but after I press enter, it thinks that I've presses something else, which makes it completely skip the cin to get the string value. But, there is something weird with this, if I type "10 hello world" it does everything correctly. Well, with the exception that it needs to be in the same line as the number to reach the function.
Solved: The use of getline(cin, strinput) works perfectly fine, if you're not using user input before hand. If you are, you're going to need a cin.ignore before the getline(). As stated in the comment by my best answer.
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
using namespace std;
//~~~Initialize all functions
int chapter10();
//~~~Initializing complete
int main() {
srand(time(0)); //makes rng thingy work instead of choose same numbers cause it doesn't do it on its own. lol
cout << "Enter the chapter number you need to look at: ";
int chapterNumber;
cin >> chapterNumber;
switch (chapterNumber) {
case 1: testingStuff(); break;
case 9: chapter9(); break;
case 10: chapter10(); break;
default: cout << "You chose an invalid chapter number, reload the program."; break;
}
system("pause");//So console doesn't close instantly cause that's not annoying at all...
}
int chapter10() {
string strinput;
char charstr[10000];
int numwords=1;
cout << "Enter a phrase." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, strinput);
const int size = strinput.size() + 1;
strcpy_s(charstr, strinput.c_str());
for (int i = 0; i != size; i++) {
if (*(charstr + i) == ' ' & *(charstr + (i+1)) != ' ' )//the & is fail safe so multiple space no ++numwords
numwords++;
}
cout << "There are " << numwords << " words in that string." << endl;
return 0;
}
The way I have my code written was I used a switch/case to reach my function. This required user input, which in turn caused my program to 'think' I was still typing for the second input required in the chapter10 function.
Adding in the line of code: cin.ignore(numeric_limits<streamsize>::max(), '\n'); allowed me to cancel the input, and start a new one.
If you want to get all characters an end-user enters on a single line, use getline: instead of cin >> strinput write this:
getline(cin, strinput);
The fact that it is actually std::getline(std::cin, strinput) makes no difference, because your code uses std namespace anyway. In case you were wondering what std:: prefix is, it's a namespace of the Standard C++ library.
You can use getline() function
It copies into a string till a newline is reached or delimiter is found - so it will accept all the spaces till newline is reached
http://www.cplusplus.com/reference/string/string/getline/
or you can also use cin.getline() as shown here -
std::cin input with spaces?
use:
cin >> noskipws >> strinput;
Use std::getline() function. Example:
#include <iostream>
#include <vector>
#include <sstream>
void WordCounter(
const std::vector<std::string> & lines) {
for (int i = 0; i < lines.size(); ++i) {
std::istringstream iss(lines[i]);
std::string word;
int count = 0;
while (iss >> word) {
++count;
}
std::cout << "Line #" << i << " contains " << count << " words." <<
std::endl;
}
}
int main() {
std::string line;
std::vector<std::string> lines;
while (std::getline(std::cin, line)) {
lines.push_back(line);
}
WordCounter(lines);
return 0;
}

Input With Spaces is Clobbering the Next Input (using cin)

I ran into an interesting problem when playing around with input streams in C++.
I know that if you attempt to enter a string that contains spaces using cin it will truncate the string at the first space unless you use getline to get the string.
However I found that even more unexpected results can occur ... If you have a second cin after the first one, and the first cin has spaces in it's input, the second input is skipped and its value is clobbered!
Why does this happen?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString;
int myInt;
// I know this will cut off the end of the string
cout << "Enter a string with spaces: ";
cin >> myString;
cout << endl;
cout << "Enter an integer: ";
cin >> myInt;
cout << endl;
cout << "String: " << myString << endl;
cout << "Int : " << myInt << endl;
return 0;
}
Output:
Enter a string with spaces: This is a string
Enter an integer:
String: This
Int : -858993460
Is there a way to trap on this error so an ignorant user doesn't enter a string with spaces and break an entire program?
Reading from cin does not read a whole line and then only return part of it. Conceptually, it reads a 'token', usually understood to mean a whitespace-separated string, and then parses it into whatever type you are reading. It has no concept of a 'line'. All the input lines are one consecutive stream of tokens. So after reading a string ("This"), the next token is "is", which of course cannot be parsed as an int, and thus the error.

String not turning blue and only reading up to space

Here's my actual code, it's skipping the getline(cin,phrase) completely..
maybe there's something else wrong with it, but I can't really find anything wrong.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream outFile;
string file_name;
string phrase;
int number;
cout << "What file would you like to write into? ";
cin >> file_name;
outFile.open(file_name);
if(!outFile)
{
cout << "Error, could not find file. Press enter to self destruct. " << endl;
return -1;
}
cout << "What would you like to write? ";
getline (cin, phrase);
cout << "How many times? ";
cin >> number;
while(number != 0)
{
outFile << phrase;
number = number - 1;
}
system("pause");
return 0;
}
cin would read as far as whitespace is not there in your input string. To get around that you can use
getline( cin, cookie ).
OR
char input[100];
cin.getline(input,100);
EDITED AS TO CLARIFY:-
Show me the output for this :-
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cookie;
getline ( cin, cookie );
cout << cookie;
system("pause");
return 0;
}
The >> operators read formatted input in term of "space separated items", so
aaaaa bbbb 123
are actually three distinct elements. The first two can be string, the third can be a string or whatever numeric scalar type.
If you want to consider spaces as part of the read, the proper function shold be getline