C++ 菜单和数组中的字符串搜索

标签 c++ arrays sorting search

当我输入此代码并尝试运行它时,当用户选择选项 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/

相关文章:

c++ - 模板函数参数和模板成员函数参数

PHP数组排序异常

java - 如何在JAVA中一次传递一个类的两个单独实例来对该类中的一些数据进行排序

sorting - 使用顶部的确切输入对预先输入的建议进行排序

c++ - void 函数调用不起作用 C++

c++ - 如何设计一个Qt前后端分离的程序?

c++ - C++ 的 CXX 测试框架

arrays - golang 中是否有任何函数可以发现值是否在数组中?

c# - C# 中的多维数组

arrays - jsonb vs jsonb[] 用于客户的多个地址