尝试使用“while(COM!=”Y“||”N“)完成由用户输入确定的循环”

时间:2015-03-22 12:40:12

标签: c++ oop while-loop char boolean

所以我遇到的问题是在我的班级IOutro中,在它的函数commandInput()中,我的意图是创建一个简单的基于命令的循环,询问用户是否愿意再次使用该程序或关闭它。

我对这个程序的目标是只使用类来存储函数,我唯一想要的就是调用这些函数的对象。只是第一次尝试使用OOP。

所以,当我试图运行它时,错误已经到了。

 ||=== Build: Debug in Tutorials (compiler: GNU GCC Compiler) ===|
C:\Users\Jason\Documents\Tutorials\main.cpp||In function 'int main()':|
C:\Users\Jason\Documents\Tutorials\main.cpp|57|error: could not convert 'COM.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >(((const char*)"Y"))' from 'std::basic_string<char>' to 'bool'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我不确定我应该注意什么,我理解它是我使用的字符串的问题,它也给了我一次错误,之前有些更改说它无法识别{{1}运营商,我在想!=意味着&#34;不等于&#34;而!=表示&#34;或&#34; ((基本上,如果左边不是真,检查正确的值,如果LEFT值为真,则忽略正确的值。)

我确信我遗漏了一些简单的信息,或者我可能没有找到正确的信息。有人可以赐教。

这不是作业,我不是学生,我自学c ++,这样的地方基本上是我找到答案的唯一地方。

||

1 个答案:

答案 0 :(得分:1)

让我们看一下代码中的问题。

首先,你不需要COM成为一个字符串,将它声明为一个字符就足够了,比如

char COM = 'Y';

接下来,您应该从{/ 1}更改{/ 1}}中的while循环条件

commandInput()

while (COM != "Y" || "N" )

你的情况不对,你需要检查两者,如上所述。

现在您可能想知道为什么我将while (COM != 'Y' && COM != 'N' ) // if you don't want it to be case sensitive, then you will have to add small letters to the condition as well 更改为||。这是因为如果它是&&,如果||不是COM'Y'不是COM,则循环将继续。现在就这样想,如果'N'COM,那么它不是'Y',如果它不是'N',那么你的while循环中的条件就会满足,因此,它只是继续。

现在,让我们看看下一个问题。在'N',您有

main()

while (COM = "Y") 是赋值运算符,如果要检查是否相等,则需要使用=。那是

==

简而言之,您的代码的固定版本将是(我删除了您的评论并添加了我已做出更改的评论,有三行更改)

while (COM == 'Y' )

请注意,对于此代码,您不需要#include <iostream> using namespace std; int A; int B; char COM = 'Y'; // changed to char class Arith{ public: int sum(int A, int B){ int C = A + B; return C; } void calc(){ cout << "Enter a number for A: "; cin >> A; cout << endl; cout << "Enter a number for B: "; cin >> B; cout << endl; cout << "The sum is: " << sum(A, B)<<endl; } }; class IOutro{ public: void goodbye(){ cout << "Thank you!" << endl; } void welcome(){ cout << "Welcome!" << endl; } void commandInput(){ cout << "\nWould you like to continue?" << endl; cout << "Please type 'Y' for Yes, and 'N' for No." << endl; cin >> COM; while ( ( COM != 'Y' && COM != 'y' ) && ( COM != 'N' && COM != 'n' ) ) { // made changes here cout << "\nWould you like to continue?" << endl; cout << "Please type 'Y' for Yes, and 'N' for No." << endl; cin >> COM; } } }; int main(){ IOutro IObject; Arith ArithObject; while (COM == 'Y' || COM == 'y' ){ // made changes here IObject.welcome(); ArithObject.calc(); ArithObject.sum(A,B); IObject.commandInput(); } IObject.goodbye(); return 0; } ,并且还使代码对大小写不敏感(即#include<string>'Y''y'或{ {1}})

这将消除你得到的那个令人讨厌的错误。

嗯,希望能解决问题(好吧,这解决了我的问题)