Why does this not ask user for another input? - c++

This part of a larger project. Right now it's supposed to ask user for a string, calculate how many words are in it, print out the # of words, ask user if they want to do it again, then if they want to, ask for another string, and so on. But this only works fine the first time. After that, it takes the answer to the yes/no question as the test string. For example: I like coding. 3. Again? Yes/no. Yes. 1. Again? Yes/no... Can someone tell me how to fix this glitch?
#include <iostream>
#include <string>
using namespace std;
string original[10] = { "hello", "sir", "madam", "officer", "stranger", "where", "is", "the", "my", "your" };
string translated[10] = { "ahoy", "matey", "proud beauty", "foul blaggart", "scurvy dog", "whar", "be", "th'", "me", "yer" };
string input;
string ans;
bool playAgain()
{
cout << "Another? yes/no: ";
cin >> ans;
if (ans.compare("yes") == 0) { return true; }
if (ans.compare("no") == 0) { return false; }
}
int getNumOfWords(string input)
{
int numOfSpaces = 0;
string current;
for (int i = 0; i < input.length(); i++)
{
current = input.at(i);
if (current.compare(" ") == 0)
{
numOfSpaces++;
}
}
return numOfSpaces + 1;
}
void play(string input)
{
int numOfWords = getNumOfWords(input);
cout << numOfWords << endl;
}
void start()
{
getline(cin, input);
play(input);
}
int main()
{
bool playing;
do
{
start();
playing = playAgain();
} while (playing);
return 0;
}

When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() beore calling getline()
void start()
{ cin.ignore();
getline(cin, input);
play(input);
}

It's because of the difference between getline and cout. The former reads in the entire line up to and including the terminating \n, while cout will read only up to the \n or whitespace. The cin in your code reads in yes or no to ans (try printing it out immediately afterwards), but it doesn't account for the \n. Thus, when you call getline it finds the \n waiting in stdin, and so reads that into input instead of blocking until cin wasn't empty.

Related

std::getline not re-requesting user input in while loop [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I am trying to write a program where a user is asked for input and then I check if the 2 sub strings (splitting in half) is the mirror image. I want to loop continually until a user stops entering in input but my code is not looping correctly. The code works fine on the first iteration of the while loop, but then during the second iteration of the while loop, getline() does not re-request user input, it just sets std::string input to "".
I'm sure I am missing something obvious.
Code
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
bool compareMirrorString(const std::string&, const std::string&);
int main()
{
std::string input;
string first_string;
string second_string;
bool result;
int input_length;
int first_string_length;
std::string quit;
cout << "Enter 2 strings to compare, seperated by a # e.g. \"abc#cba\"." << endl;
while ( true )
{
std::getline(std::cin, input);
//split string into its two component parts
input_length = input.length();
first_string_length = input_length / 2;
first_string.assign(input, 0, first_string_length);
second_string.assign(input, first_string_length + 1);
//test if two strings are mirror images of each other
result = compareMirrorString(first_string, second_string);
if (result) {
cout << "Yes they match.";
}
else {
cout << "No they do not match.";
}
cout << "\nDo you want to test another string? Y for yes, q to quit." << endl;
cin >> quit;
if (quit == "q" or quit == "Q" or quit == "quit" or quit == "Quit" or quit == "QUIT"
or quit == "no" or quit == "No")
{
break;
}
else
{
cout << "Enter another 2 strings to compare, seperated by a # e.g. \"abc#cba\"." << endl;
}
} //end of while
return 0;
}
//is second a mirror image of first?
bool compareMirrorString(const std::string& first, const std::string& second)
{
if (first.length() != second.length()) {
return false;
}
//put first_string on stack
std::stack<char> stackChar;
for (auto elem : first){
stackChar.push(elem);
}
int size = stackChar.size();
//compare first and second strings
bool compare_equal = true;
for (int i = 0; i < size; i++)
{
if (stackChar.top() == second[i])
{
stackChar.pop();
}
else
{
compare_equal = false;
break;
}
}
return compare_equal;
}
In the first iteration of the loop:
cin >> quit;
will read up to, but not including the newline character.
In the second iteration of the loop:
std::getline(std::cin, input);
will read that newline character, and hence read an empty string into input.
There are several ways to fix this
You could use getline to read the string quit
You could read input again, if it happens to be an empty string.
You could call cin.get(); after the cin >> quit to clear the newline.

How to make user input numbers only in C++?

So far, this is my code:
while(bet > remaining_money || bet < 100)
{
cout << "You may not bet lower than 100 or more than your current money. Characters are not accepted." << endl;
cout << "Please bet again: ";
cin >> bet;
}
It works fine but I'm trying to figure out how to make it loop if the user inputs anything that isn't a number as well.
When I press a letter or say a symbol/sign, the code just breaks.
Using the function
isdigit()
This function returns true if the argument is a decimal digit (0–9)
Don't forget to
#include <cctype>
I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a double.
#include <string>
#include <sstream>
int main()
{
std::string line;
double d;
while (std::getline(std::cin, line))
{
std::stringstream ss(line);
if (ss >> d)
{
if (ss.eof())
{ // Success
break;
}
}
std::cout << "Error!" << std::endl;
}
std::cout << "Finally: " << d << std::endl;
}
A good way of doing this is to take the input as a string. Now find the length of the string as:
int length = str.length();
Make sure to include string and cctype. Now, run a loop that checks the whole string and sees if there is a character that is not a digit.
bool isInt = true;
for (int i = 0; i < length; i++) {
if(!isdigit(str[i]))
isInt = false;
}
If any character is not a digit, isInt will be false. Now, if your input(a string) is all digits, convert it back to an integer as:
int integerForm = stoi(str);
Store integerForm in your array.

Why does this while loop output the same thing no matter what you input?

I have a program that does three things. Asks you how many variables you wan't, ask you to input each variable, then stores it in a vector. I have put some code that checks if your input is correct, and if it isn't, re-loops the code asking for your variable. The problem I am having is that when you type anything in around the second variable, it asks you to try again infinitely.
For instance, if I typed these values into the input:
Variable amount: 5
Please input variable 1: 8
Please input variable 2: 8
ERROR, PLEASE ENTER ONLY VALID SYMBOLS
---------------------
Please input variable 2:
It would keep outputting ERROR, PLEASE ENTER ONLY VALID SYMBOLS over and over again no matter what you typed. The code is down below, and if you have a better name for this question please let me know. (I'm not really sure what to call this)
#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
int inputErrorMessage()
{
cout << "\n ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
cout << "--------------------- \n";
return 0;
}
int main()
{
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 0;
int choice = 0;
vector<int> userNums;
double input = 0;
string checktotVar = "";
string checkInput = "";
string sym = "";
bool valid = false;
stringstream sstotVar;
stringstream ssinput;
if (choice != 6) {
while (!valid) {
valid = true;
// Ask user for how many variables they want then record it
cout << "Variable amount: ";
getline(cin, checktotVar);
sstotVar << checktotVar;
sstotVar >> totVar;
if (sstotVar.fail() || totVar <= 0) {
inputErrorMessage();
valid = false;
sstotVar.clear();
sstotVar.ignore();
}
}
valid = false;
while (!valid) {
valid = true;
// Ask the user for each variable, then record it into the array
for (int i = 0; i < totVar; ++i) {
cout << "Please input variable " << varNum << ": ";
getline(cin, checkInput);
ssinput << checkInput;
ssinput >> input;
if (ssinput.fail()) {
inputErrorMessage();
valid = false;
ssinput.clear();
ssinput.ignore();
}
if (valid == true) {
userNums.push_back(input);
varNum++;
}
}
}
}
}
ssinput >> input;
reads the one thing in ssinput right to the end of the stream while leaving the read valid. The next time around
ssinput << checkInput;
can't write into the stream because the stream hit the stream's end. That means the read also fails and
if (ssinput.fail()) {
enters the body of the if where the program clears the error
ssinput.clear();
and then promptly reads off the end of the stream with
ssinput.ignore();
causing the error all over again.
Quickest solution:
Recreate
stringstream ssinput;
on each loop iteration. So
stringstream sstotVar;
//stringstream ssinput; gone from here
and
getline(cin, checkInput);
stringstream ssinput(checkInput); // and now tighter scope recreated each loop.
ssinput >> input;
Also by keeping the stream around without emptying it out it can get very., very big.
You can also simplify your logic around
while (!valid) {
and eliminate some repeated code by moving the read validation into it's own function
int getMeANumber(const std::string & message, int min)
that loops until it gets a number and then returns that number. For example:
int getMeANumber(const std::string & message, int min)
{
while (true)
{
cout << message;
string checktotVar;
getline(cin, checktotVar);
stringstream sstotVar(checktotVar);
int totVar;
sstotVar >> totVar;
if (!sstotVar || totVar <= min)
{
inputErrorMessage();
}
else
{
return totVar;
}
}
}
Now main is this itty-bitty tiny lil' thing.
int main()
{
int choice = 0;
vector<int> userNums;
if (choice != 6)
{
int totVar = getMeANumber("Variable amount: ", 0);
for (int i = 0; i < totVar; ++i)
{
stringstream varname;
varname << "Please input variable " << i+1 << ": ";
userNums.push_back(getMeANumber(varname.str(), numeric_limits<int>::min()));
// numeric_limits<int>::min requires #include <limits>
}
}
}
Here are the issues with this code.
In this part:
if (valid == true) {
userNums.push_back(input);
varNum++;
}
you forgot to add an ssinput.clear(). This will reset the stream state (clear the error flags), otherwise you cannot use it again. That is why it stops working at the second input.
In addition, even though this works, you are pushing back a variable that you declared as double into a vector of ints. That is bound to cause issues if this was intended to store double variables, instead of truncating them and storing them as ints.
It should be:
#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
int inputErrorMessage()
{
cout << "\n ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
cout << "--------------------- \n";
return 0;
}
int main()
{
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 0;
int choice = 0;
vector<int> userNums;
double input = 0;
string checktotVar = "";
string checkInput = "";
string sym = "";
bool valid = false;
stringstream sstotVar;
stringstream ssinput;
if (choice != 6) {
while (!valid) {
valid = true;
// Ask user for how many variables they want then record it
cout << "Variable amount: ";
getline(cin, checktotVar);
sstotVar << checktotVar;
sstotVar >> totVar;
if (sstotVar.fail() || totVar <= 0) {
inputErrorMessage();
valid = false;
sstotVar.clear();
sstotVar.ignore();
}
}
valid = false;
while (!valid) {
valid = true;
// Ask the user for each variable, then record it into the array
for (int i = 0; i < totVar; ++i) {
cout << "Please input variable " << varNum << ": ";
getline(cin, checkInput);
ssinput << checkInput;
ssinput >> input;
if (ssinput.fail()) {
inputErrorMessage();
valid = false;
}
if (valid == true) {
userNums.push_back(input);
varNum++;
}
ssinput.clear();
}
}
}
}
EDIT: You need to clear the stringstream on each iteration of the loop, otherwise you're not writing to an empty stream when you grab the next input from the user, which is what's causing the .fail() method to return true after the first iteration of the loop.

Why is a space in the string making my code loop infinitely? [duplicate]

This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 6 years ago.
I have the following code which simply takes a string and find each character's index in the alphabet.
void encrypt()
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
string word;
vector<char> temp;
char a, b;
cout << "Enter string to encrypt: \n";
cin >> word;
for (int i=0; i<word.length(); i++)
{
bool t = false;
a = word[i];
for (int j=0; j<alpha.length(); j++)
{
b = alpha[j];
if (a == b)
{
cout << a << "'s index = " << j+1 << endl;
t = true;
}
}
if (t == false)
{
cout << "space here\n";
}
}
}
when i input a word/string with no space the code works fine but when i input a string with a space the program goes into an infinite loop.
edit main() added due to request:
main()
{
int a;
bool b = false;
while (b == false)
{
cout << "1. Encrypt a string\n";
cout << "2. Decrypt a string\n";
cout << "3. Exit\n";
cout << endl;
cin >> a;
cout << endl;
if (a == 1)
{
encrypt();
}
else if (a == 2)
{
decrypt();
}
else if (a == 3)
{
b = true;
}
}
return 0;
}
cin >> word;
will read only the first word and leave the second word in the input stream. After that, the call
cin >> a;
will result in an error unless the second word starts with a number. Once the program enters a state of error, nothing is read and the program stays in a loop.
To diagnose problems like these, always check the state of the stream after a read operation.
if ( cin >> word )
{
// Use word
}
else
{
// Deal with error.
}
if ( cin >> a )
{
// Use a
}
else
{
// Deal with error.
}
To address your real problem, don't use operator>> to read space separated string. Use getline (and use a variable name different from word).
std::string str;
if ( getline(std::cin, str) )
{
// Use str
}
else
{
// Deal with error.
}
However, in order to use getline successfully, you have to make sure that after a is read, you ignore the rest of the line. Otherwise, the rest of the line will be read by getline.
if ( cin >> a )
{
// Ignore rest of the line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Use a
}
else
{
// Deal with error.
}
Replace cin >> word; with getline(cin, word);. It will accept a line as input. Which will resolves your input containing spaces.
As far as infinite loop concern, clear the error bits on the stream cin.clear();
You can check whether cin is accepting the space separated string completely, by doing a cout instantly after the cin. If cin is not accepting the space separated string, then try using getline
Issue resolved:
Use the following:
cout << "Enter string to encrypt: ";
scanf(" %[^\n]s",word);
for (int i=0; word[i]!='\0'; i++)
{
use
include <cstdio>
Hope this solves the problem!! I will get back to you with the solution using string..

String length getting reduced by using getline?

I am using getline and ignore but something is not working properly,
Below is the sample code which am not able to understand how it is working.
int main()
{
string str;
int t,length;
cin>>t; // t is the number of test cases
while(t--!=0)
{
cin.ignore();
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
Sample output:
2
hey hi
length 6
hey hi
length 5
Why is the length decreasing? Is this because of getline and ignore function? Any help would be appreciated.
The reason it is giving a different length is becaus your ignore() function ignores only one character. The first time round it ignores the return key you pressed after entering the number. But std::getline() deletes the return character for you. So the second time round ignore() deletes the first letter of your string making it "eh hi".
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// first removed RETURN character after removes first letter
cin.ignore();
getline(cin, str);
length = str.size();
cout << "length = " << length;
}
}
Try using this instead:
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// cin.ignore(); // dont do this here please
// cin >> ws skips all whitespace characters
// including the return character
getline(cin >> ws, str);
length = str.size();
cout << " length = " << length;
}
}
Alternatively (maybe better) you can move the ignore() function out of the loop to where t is really needed:
#include <limits>
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
// ignore as many characters as necessary including the return
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t-- != 0)
{
// cin.ignore(); // not here
getline(cin, str);
length = str.size();
cout << " length = " << length;
}
}
The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); looks complicated but it is the only way to guarantee that any spurious characters (like spaces) are removed. You can probably get away with just cin.ignore() for the exercise if you want.
Read up on std::istream::ignore()
cin.ignore() defaults to ignoring one character.
If you output your string each time, you'll see that in later cases the string is equal to "ey hi". The h is being dropped.
The value of the string held by cin drops its first character before being passed to getline.
Since you're using getline, you can simply remove the cin.ignore() from your loop and your program should work as intended.
However, you should also change your cin>>t; line. In this case, the ignore() is dropping the line return after the input value 2. A stringstream here allows for a getline(...) function, or alternatively you can use cin.ignore(str.max_size(), '\n');.
In the case of the stringstream, your code would become:
#include <sstream> // stringstream
#include <string> // std::string
#include <iostream> // cin
int main()
{
string str;
int t,length;
getline(cin, str);
std::stringstream stream;
stream << str;
if (!(stream >> t)) {
// Couldn't process to int
}
// cin>>t; // t is the number of test cases
// No longer need this line.
while(t--!=0)
{
// cin.ignore(); Drop this too
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
If you are not interested in whitespace,
then use getline(cin >> ws, str)