c++ - 为什么这不要求用户进行其他输入?

标签 c++ c++11 visual-c++

这是一个更大项目的一部分。现在它应该向用户询问一个字符串,计算其中有多少个单词,打印出单词的#,询问用户是否想再做一次,然后如果他们想,再询问另一个字符串,等等.但这只在第一次时有效。之后,它将是/否问题的答案作为测试字符串。例如:我喜欢编码。 3.又是?是/否。是的。 1.又是?是/否...有人可以告诉我如何解决这个问题吗?

#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;
}

最佳答案

cin.getline() 从输入中读取时,输入流中留下了一个换行符,因此它不会读取您的 C 字符串。在调用 getline()

之前使用 cin.ignore()
void start()
{   cin.ignore();
    getline(cin, input);
    play(input);
}

关于c++ - 为什么这不要求用户进行其他输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29111118/

相关文章:

c++ - 我的汇编函数推送数据两次

c++ - 使用单独的线程从文件预加载数据

c++ - 将模板参数与模板类型匹配

c++ - 静态对象的奇怪输出

c++ - Cpp/Cli 项目中的 Boost::Log 错误

c++ - 在C++中移动和复制构造函数

c++ - -llibrary 如何确定和定位对象文件名

c++ - 无法编译 KAA C++ SDK

c++ - 有没有办法在声明时用缓冲区初始化数组?

c++ - 如何将整个 Visual c++ 项目加载到 Enterprise Architect 中以对其进行逆向工程?