我是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;
}
答案 0 :(得分:1)
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!
答案 1 :(得分:1)
您的问题是您在if
声明中的比较:
if (CourseTitle == "x" && "X")
正确的语法是:(变量操作符变量)&amp;&amp; (变量操作符变量)
语法更正:
if ((CourseTitle == "x") && (CourseTitle == "X"))
存在一个逻辑问题,因为变量不能同时等于两个值。
也许你想要:
if ((CourseTitle == "x") || (CourseTitle == "X"))
表示一个 OR 表达式为true。
您可以通过将字符串转换为全部大写或全部小写来消除这两个比较。在网上搜索“C ++ string transform tolower toupper”。