正在检查字符串以匹配Char变量

Checking a string to match a Char variable

本文关键字:Char 变量 检查 字符串      更新时间:2023-10-16

我已经编写了一个短程序,它接受用户输入,然后检查字符串是否与用户输入匹配,但我需要添加另一个函数来检查,确保用户输入在字符串中,如果不返回错误。

这是我的代码供参考:

const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
    char letter; //Variable holding user entered letter 
    cout << "Please enter letter in the aplhabet:" << endl;
    cin >> letter;
    cout << "The Position of " << letter << " in the string is: " << ALPHABET.find(letter) << endl;
    return 0;
}

我认为我应该添加一个if/else语句,它首先检查输入是否正确,是否输出字符串中的位置,如果没有返回并出错。

如果你想变得花哨,你可以编写自己的函数。但是,string::find()可以。您只需要检查返回的索引是否有效。

// Example program
#include <iostream>
#include <string>
using namespace std;

const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
    char letter; //Variable holding user entered letter 
    string::size_type index; //Index where char is found in string
    cout << "Please enter letter in the aplhabet:" << endl;
    cin >> letter;
    index =  ALPHABET.find(letter);
    if (index == string::npos)
        cout << "Error, letter not found" << endl;
    else
        cout << "The Position of " << letter << " in the string is: " << index << endl;
    return 0;
}

if/else语句听起来不错。如果这不起作用,还有其他多种方法可以。