当我输入此代码并尝试运行它时,当用户选择选项 1 输入一些文本和要在其文本中搜索的字符串时,它不起作用。它输出“输入文本”,然后立即输出“输入要搜索的字符串”,而不给用户输入一些文本的机会。怎么了?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
最佳答案
这是因为 cin >> choice
为用户输入的选择读取当前输入行的一部分。第一个getline()
call 在用户输入选择后立即读取输入行的剩余部分。选择后您需要忽略输入行的其余部分。
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
您还需要添加 #include <limits>
到代码的开头以便引入 numerical_limits
.
关于C++ 菜单和数组中的字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198161/