繁体   English   中英

C ++-我在调试器中看到不正确的值(MS VS 2015)

[英]C++ - I see incorrect value in debugger (MS VS 2015)

第一次使用C ++文件流。 我有一个问题。
(Windows 8.1 x64,MS VS 2015,但mscrt v.120(来自MS VS 2013)x64)

fin >> m行之后, m等于0xccccccccccc ,但必须等于570

函数fscanf可以正常工作并返回m=570
函数std::getline (fin, line)也返回line="570"

跟随第一个int的Doubles将被很好地读取。

编辑:我不会尝试通过printf检查变量的值。

为什么输入运算符不能按预期工作? 我不明白什么

  #include <string>
  #include <fstream>
  #define WIN32_LEAN_AND_MEAN
  #define _UNICODE
  #include <windows.h>
  #include <tchar.h>

  typedef std::basic_string<TCHAR> tstring;

  size_t  m;
  tstring filename;
  // --------------------------------
  std::ifstream  fin (filename, std::ios_base::in);
  if ( fin.is_open () )
  {
    if ( fin >> m )  // !!!
    { angles.resize (m); }
    else
    { throw std::exception ("ifstream error"); }

    double angle = 0.;
    while ( fin >> angle )
    { angles.push_back (angle); }

    double angle = 0.;
    while ( fin >> angle )
    { angles.push_back (angle); }
    // --------------------------------
    size_t m = angles.size (); / <--- HERE 
    //  is the DEFINITION of the new variable with the same name.
    //  It is created on a stack, so before it's been initialized,
    //  it has the value = 0xcccccccc.
    frames.resize (m);
    // --------------------------------
    for ( size_t i = 1U; i < m; ++i )
    { frames[i] = i; }
    // --------------------------------
  }
  else
  { throw std::exception ("ifstream: input error."); }
}

文本文件不包含BOM表或其他内容...这是二进制视图:

输入数据的二进制视图

当使用std::ifstream打开文件时,文件名参数必须是const char*类型的C字符串。

我还建议您使用std::basic_string<TCHAR>.c_str()或仅使用常规std::string.c_str()

正如我在注释中错误地写道: MS VS Debugger的内部变量中的问题 不出所料是我的错。

我只能在DEBUG版本中看到调试器中变量的不正确值。 在RELEASE中,变量在调试器中具有正确的值。

因此,解决方案是重命名变量以在调试器中看到正确的值。


一个函数的所有代码:

{
  std::ifstream  fin (filename, std::ios_base::in);
  // --------------------------------
  if ( fin.is_open () )
  {
    size_t  m;
    if ( fin >> m ) // << 0xccccccccc
    { angles.reserve (m); }
    else
    { throw std::exception ("ifstream: input error."); }

    double angle = 0.;
    while ( fin >> angle )
    { angles.push_back (angle); }
    // --------------------------------
    size_t m = angles.size (); // <--- HERE 
    //  is the DEFINITION of the new variable with the same name.
    //  It is created on a stack, so before it's been initialized,
    //  it has the value = 0xcccccccc. That I can see.
    frames.resize (m);
    // --------------------------------
    for ( size_t i = 1U; i < m; ++i )
    { frames[i] = i; }
    // --------------------------------
  }
  else
  { throw std::exception ("ifstream: input error."); }
}

我建议您将m变量的数据类型更改为int,因为据我所知,函数size()返回一个整数并将数字存储在变量m中。 然后使用以下语法创建数据类型为size_t的变量测试:size_t test = m。 如果是调试器的错误,请尝试使用sizeof()而不是size_t数据类型。 这意味着前一个可以这样写:sizeof(m)并将其存储在变量中。 希望我能对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM