【问题标题】:reading in file and storing it to variables, then checking using if Statement. Using ifstream读取文件并将其存储到变量中,然后使用 if 语句进行检查。使用 ifstream
【发布时间】:2018-06-16 22:44:52
【问题描述】:

好的,所以我正在尝试从文本文件中读取数据并将其存储到变量中。然后我想检查是否(变量 i == x)。但是,当我执行变量时,我不等于 x,即使我已经通过调试器并且它确实如此!有任何想法吗?变量是char类型。

        while (inFile >> type >> xpos >> ypos >> zpos >> scale)
    {
        if (type == "Floortile")
        {

            Model* floor = new Model(g_pD3DDevice, g_pImmediateContext);
            if (FAILED(floor->LoadObjModel("assets/Model/Floor_tile.obj", "assets/Textures/Groundtex.bmp")))
            {
                DXTRACE_MSG("Failed to load model");
            }
}

【问题讨论】:

  • "Floortile" 是字符串文字,char 的常量数组。如果不编写自定义重载,则无法与单个 char== 进行比较。
  • 另一方面,如果通过“变量是char类型”。你的意思是type 也是一个char 数组,那么你遇到了一个稍微不同的问题,并且不小心比较了两个数组的地址。在这种情况下,您可能希望将std::string 用于type。它可以与带有== 运算符的字符串文字进行比较,而无需额外的代码。
  • 非常感谢,这很有意义,但是我设法找到了解决方法:)
  • 在这种情况下建议共享解决方案或删除问题。离开这个悬空没有意义。
  • 解决方法如下

标签: c++ if-statement char ifstream directx-11


【解决方案1】:

使用 strstr(str1, str2) 方法解决了我的问题,str1 是要扫描的字符串,而 str2 字符串包含要匹配的字符序列。这也适用于 char[]。 谢谢大家的意见:)

 if ( strstr("Floortile",type) != 0)

【讨论】:

  • 这对于像“oo”这样的输入将失败,因为“oo”将在“Floortile”中找到并返回非空结果。 strcmp("Floortile",type) == 0 会更合适,因为匹配必须准确。 strcmp 文档:en.cppreference.com/w/cpp/string/byte/strcmp
  • 我建议您阅读strstr() 的文档。我不认为它做你认为它做的事。
猜你喜欢
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 2022-09-29
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2016-04-27
相关资源
最近更新 更多