字符串和布尔值(Int 条件为假)C++
String and Bool (Int Condition to be false) C++
>我是C++新手,我尝试搜索,但我不知道要搜索什么。不好意思。我的问题是:
-
当我设置 bool 条件 false 时,它仍然需要我输入 2 x 来终止编译器。为什么会这样?(我尝试使用 cin.fail () 但它不起作用)
-
当我打印课程列表时,它列出了应该终止程序的课程(即当您按 x 时)。我该如何纠正?谢谢你的帮助。
int main(void) { // Gather list of courses and their codes from user, // storing data as a vector of strings const string DegreeCode("PHYS"); string CourseTitle; int CourseCode(0); vector <string> CourseList; vector <string> :: iterator iter; bool not_finished(true); do { if (CourseTitle == "x" && "X") { not_finished=false; } else { cout<<"Please enter a course code and a course title (or x to finish): "<<endl; cin>>CourseCode; cin.sync(); cin.clear(); getline(cin , CourseTitle); ostringstream oss; string outputCourseList (oss.str ()); oss << DegreeCode << " " << CourseCode << " "<< CourseTitle; CourseList.push_back (oss.str ()); cout <<outputCourseList <<endl; oss.str(""); //clear oss content } } while(not_finished); // Print out full list of courses cout<<"List of courses:n"<<endl; for (iter = CourseList.begin(); iter != CourseList.end(); iter++) cout<<(*iter)<<endl; return 0; }
你的问题是你在if
语句中的比较:
if (CourseTitle == "x" && "X")
正确的语法是:
(变量运算符变量)&&(变量运算符变量)语法已更正:
if ((CourseTitle == "x") && (CourseTitle == "X"))
存在逻辑问题,因为变量不能同时等于两个值。
也许你想要:
if ((CourseTitle == "x") || (CourseTitle == "X"))
这意味着一个 OR 表达式为真。
您可以通过将字符串转换为全部大写或全部小写来消除这两个比较。 在网络上搜索"C++字符串转换为下到上"。
if (CourseTitle == "x" && "X")
{
not_finished=false;
}
自
if (strcmp(CourseTitle.c_str(), "x") == 0 || strcmp(CourseTitle.c_str(), "X") == 0)
{
not_finished=false;
}
== 是一个指针比较,几乎从来都不是真的..."x" == "x" 甚至会是假的,除非你擅长编译器标志
确保
#include <string.h> //<----.h is needed!
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 我提出什么条件才能再加5%的折扣
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 没有超时的C++条件变量
- 正在LLVM中检测整数比较条件
- 在条件变量中触发错误信号的频率是多少