C++ 如果语句不起作用
C++ If statement won't function
//Writing a letter
#include <iostream>
using namespace std;
int main() {
string first_name; //Name of addressee
string friend_name; //Name of a friend top be mentioned in the letter
char friend_sex, m, f; //variable for gender of friend
friend_sex = 0;
cout << "nEnter the name of the person you want to write to: ";
cin >> first_name;
cout << "Enter the name of a friend: ";
cin >> friend_name;
cout << "Enter friend's sex(m/f): "; //Enter m or f for friend
cin >> friend_sex; //Place m or f into friend_sex
cout << "nDear " << first_name << ",nn"
<< " How are you? I am fine. I miss you!blahhhhhhhhhhhhhhhh.n"
<< "blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.n"
<< "Have you seen " << friend_name << " lately? ";
//braces only necessary if there are more than one statement in the if function
if(friend_sex == m) {
cout << "If you see " << friend_name << ", please ask him to call me.";
} //If friend is male, output this
if(friend_sex == f) {
cout << "If you see " << friend_name << ", please ask her to call me.";
} //If friend is female, output this
return(0);
}
这是实际结果:
Enter the name of the person you want to write to: MOM
Enter the name of a friend: DAD
Enter friend's sex(m/f): m
Dear MOM,
How are you? I am fine. I miss you! blahhhhhhhhhhhhhhhhh.
blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.
Have you seen DAD lately?
该程序正在模拟一个简短的字母。输出一个单词块很容易,但是当我想在信中放置一些条件时,我就麻烦了。即使我在程序询问我时输入了friend_(m/f(,if 语句的输出也没有实现。为什么?
您正在针对未初始化的字符变量m
测试friend_sex
。您可能希望针对文本值进行测试 'm'
。这就像有一个名为 seven
的整数变量并期望它保存值7
.
char m, f
这将声明名为 m 和 f 的变量。这里的 m 和 f 是变量名,而不是值是 'm' 和 'f'。现在它们包含垃圾值。
您需要初始化它们:
char m = 'm', f = 'f'
或者你可以直接在 if 语句中放置 char 常量,而不是使用变量 m、f。
if (friend_sex == 'm') {}
你检查friend_没有初始化的 aginst m 和 f。 您可以检查文字"m"或"f">
您需要检查类似if (friend_sex == 'm')
的内容,而不是根据变量m
进行检查。基本上,您需要检查预期值。
这是您的问题:
if(friend_sex == m)
您正在比较两个变量,而不是您放入friend_sex
变量的内容。
因此,如果您将其更改为以下内容:
if(friend_sex == 'm')
现在,这将检查friend_sex
的内容是否为"m"。
您正在将friend_sex
与未初始化的变量进行比较,m
。 您应该将其与常量'm'
进行比较。 请注意单引号。
相关文章:
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 默认标签显然在 switch 语句中不起作用
- C++ 中断语句不起作用
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 使用 cin、if 语句和数组不起作用
- (C++) IF 语句似乎根本不起作用
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- QTranslator 在 if 语句中使用时不起作用
- 我的开关语句在C++中不起作用
- 切换语句不起作用 c++ 和 D:\c++ dev-c\Makefile.win 目标"abc.o"的配方失败
- C++ 默认值在开关语句中不起作用
- C++ SQLite3 准备的删除语句不起作用
- 如果语句在我的代码中不起作用
- 一个'case'在简单的'switch'语句中不起作用
- 我的程序在SCANF语句之后不起作用
- std::cin 语句不起作用 C++
- 为什么我的 if 语句不起作用
- C++ 递增在 If else 语句中不起作用
- if 语句在 for 循环中不起作用
- 我的 for 循环之后的代码不起作用,for 循环后的打印语句不会被打印