正在检查字符串以匹配Char变量
Checking a string to match a Char variable
我已经编写了一个短程序,它接受用户输入,然后检查字符串是否与用户输入匹配,但我需要添加另一个函数来检查,确保用户输入在字符串中,如果不返回错误。
这是我的代码供参考:
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语句听起来不错。如果这不起作用,还有其他多种方法可以。
相关文章:
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 如何更好地检查两个 char 变量是否在一组值中?
- 将双精度值转换为 char 变量时字符串流如何工作
- C++ 如何检查 char 变量是否未定义(未初始化)
- 在 c++ 中将 Char 数组添加到 Char * 变量
- char指针或char变量的默认值是多少
- 当对字符变量使用toupper()时,所述char变量输出多个字符.我该如何防止这种情况发生
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 程序的执行在 C++ 中输入 char 变量后结束
- 如何创建一个 char *[] 变量,以便将其传递给函数
- 将 2 位整数分配给 char 变量
- 将值设置为 char ** 变量 c++ 时出错
- 如果我们在 C++ 中声明一个起始'&'的 char 变量会发生什么?
- 在此范围C 中未声明字符串和char变量
- C++:如何将 char 变量分配给向量<char>并访问该向量的元素进行比较?
- 仅将输入的第一个字符用于 char 变量
- 在C 中使用两个CHAR变量评估布尔值
- 尚未声明char变量
- (C++)如何验证 char 变量的用户输入
- 为什么比较两次 char 变量比比较一次短变量更快