【问题标题】:C++ std::string is empty but full of '\0'C++ std::string 为空但充满 '\0'
【发布时间】:2016-11-25 14:07:35
【问题描述】:

我有一个文件,其中包含一些数字,都在一行中。我想阅读这个文件并将这一行放到一个字符串变量中。 因为它只包含一行,getline() 方法应该只工作一次

但事实并非如此。它工作两次。我注意到首先我的 string_descriptor 包含数字(所以它是好的)但是在 getline 之后再取另一行,这次它是空的,但是通过查看调试器,字符串包含很多 \O\ 像 10 次。

\O\O\O\O\O\O\O\O\O\O\O\O\O\O\O\

这让我很困扰,因为在我进行一些处理之后,我的应用程序崩溃了。

所以我正在做的是以下内容:

 fs.open (desc.c_str (), std::ios::in);
 string line;
 if(!fs.is_open())
 {
      cout<<"\n Cannot open the text.txt file";
 }
 else
 {
   std::string string_descriptor;
   while (!fs.eof ())
   {

     getline( fs , line);
     if (line != "" && line.find_first_not_of(' ') != std::string::npos && !line.empty())
     {

      string_descriptor = line;
      std::cout << "String descriptor : " << string_descriptor << std::endl;

     }
  }
}

那么为什么会这样呢?尤其是我该如何处理?我尝试通过执行以下操作来处理它,但它仍然是一样的:

if (line != "" && line.find_first_not_of(' ') != std::string::npos && !line.empty())

我检查了我的文件,目前我知道文件末尾没有空格。

感谢您的帮助

【问题讨论】:

  • 你不应该循环使用eof():stackoverflow.com/questions/5605125/…
  • 您的文件是否包含 nul 字符?
  • 目前我知道的不仅仅是数字
  • @stark 行尾有一个不可见的空格...你知道我如何检查它以备将来处理吗?

标签: c++ string crash


【解决方案1】:

为了避免循环的第二次迭代改变循环

   while (!fs.eof ())
   {

     getline( fs , line);
     //...

以下方式

   while ( getline( fs , line) )
   {
     //...

也是这个条件

if (line != "" && line.find_first_not_of(' ') != std::string::npos && !line.empty())

可以看起来更简单

if ( line.find_first_not_of(' ') != std::string::npos )

【讨论】:

  • 感谢您的修改,但即使以这种方式进行更改,但仍然遇到同样的问题...
  • @lilouch 也许文件包含两条记录,最后一条是空的。有什么问题?
  • 实际上,我的文件只包含一行数字,而我的行变量应该只包含数字,但似乎它再次循环,我从行中得到一个空字符串。我不想要那个,这就是我使用 IF 条件的原因......但我仍然得到一个充满 \0\ 的空字符串
  • @lilouch 表示文件包含多条记录,仅此而已。
  • 感谢您的回答,但在我的档案中,我只有一行而不是两行……就是这样
猜你喜欢
  • 2016-02-15
  • 2014-02-21
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多