简体   繁体   中英

Why does this not ask user for another input?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM