c++ - String 和 Bool(Int 条件为假)C++

标签 c++ string

我是 C++ 的新手,我尝试搜索但不知道要搜索什么。对不起。我的问题是:

  1. 当我将 bool 条件设置为 false 时,它​​仍然需要我输入 2 x 来终止编译器。为什么会这样? (我试过用cin.fail()但是没用)

  2. 当我打印类(class)列表时,它列出了应该终止程序的类(class)(即当您按 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++ 字符串转换为从下到上”。

关于c++ - String 和 Bool(Int 条件为假)C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919399/

相关文章:

c++ - 如何使用Wireshark帮助创建协议(protocol)模糊测试框架?

c - C 中仅通过指针在字符串数组之间交换

python - 获取 Pandas 字符串系列的加权值

c++ - 将引用分配给引用是有效操作吗?

C++ 字符串声明

c++ - 宏参数的扩展在C++中如何工作

c++ - 如何从 mpl::vector 实例化模板?

python - 从 Python 中的字符串中删除辅音

java - 为什么它不取代字符?

python - 在 Python 中如何将文件名中的某些字符列入白名单?