【发布时间】:2016-06-04 19:30:23
【问题描述】:
我对 while 循环中的 if & else 语句有疑问。
我想在我的程序中建立一些东西:
- 希望用户只输入 4 个字母字符,而不使用数字和符号。
- 将每个字母转换为整数(Ascii val.)
为便于理解,如果有混淆,
程序 1 要求输入 4 个字母的单词。 用户放置输入。如果输入至少包含:
- 一个非字母字符,然后程序向用户询问新的输入。
如果输入仅包含字母程序检查输入的字母数。
如果输入没有___:
- 4 个字母,程序要求用户输入新的输入。
否则程序继续确定每个字母的 Int 值
好的,到目前为止我的程序如下:** 不确定这是否正确
#include <iostream>
using namespace std;
int main() {
string input;
int input0 = input[0];
int input1 = input[1];
int input2 = input[2];
int input3 = input[3];
cout << "\nEnter a 4-letter word (Keep it clean!).\n";
while(cin>>input){
cout << endl << input << " has " << input.length() << " letters." << endl;
if (int(input[0]) > 64 || int(input[0]) < 91 || int(input[0]) > 96 || int(input[0]) < 123 ||
int(input[1]) > 64 || int(input[1]) < 91 || int(input[1]) > 96 || int(input[1]) < 123 ||
int(input[2]) > 64 || int(input[2]) < 91 || int(input[2]) > 96 || int(input[2]) < 123 ||
int(input[3]) > 64 || int(input[3]) < 91 || int(input[3]) > 96 || int(input[3]) < 123) {
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
}
我有 2 个错误:
错误:在 'else' 之前应为 '}'
错误:'else' 没有前面的 'if'
【问题讨论】:
-
感谢尼基的提示!设法运行程序,但我得到了一个奇怪的结果:我在询问的 4 个字符中放置了一个数字 [5tar],当它应该要求用户重试时,它仍然给出包括数字 int 值的 int 值。跨度>
-
那是因为你的逻辑是心理的,使用完全逻辑或的方式会总是导致
true。使用isalpha查看我的答案以获得更好的选择。考虑一下:什么数字大于 64,或小于 91? 当然,答案是:所有数字。
标签: c++ if-statement while-loop