这是一个更大项目的一部分。现在它应该向用户询问一个字符串,计算其中有多少个单词,打印出单词的#,询问用户是否想再做一次,然后如果他们想,再询问另一个字符串,等等.但这只在第一次时有效。之后,它将是/否问题的答案作为测试字符串。例如:我喜欢编码。 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/