jjzjj

c++ - StringStream 循环失败

coder 2024-02-23 原文

我正在阅读具有这种格式的文本文件:

grrr,some text,45.4321,54.22134

我只是将我的 double 值存储在一个字符串变量中。

为什么它只给我字符串的第一个数字?

如果我只使用一个 while 循环和这种新格式的文本文件重新开始:

21.34564

它正常工作。

问题是,sLine 与我重新开始时的值相同。不同之处在于最有可能导致问题的三个嵌套 for 循环。

这是让我得到我想要的东西的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <sstream>

using namespace std;

int main()
{
    string usrFileStr,
    fileStr = "test.txt",  // declaring an obj string literal
    sBuffer,
    sLine,
    str;

    double dValue ;

    int lineCount = 1;
    int nStart;
    istringstream issm;

    fstream inFile;                  // declaring a fstream obj
    // cout is the name of the output stream
    cout << "Enter a file: ";
    cin >> usrFileStr;

    inFile.open( usrFileStr.c_str(), ios::in ); 
    // at this point the file is open and we may parse the contents of it


    while ( getline ( inFile, sBuffer ) && inFile.eof() )
    {
          cout << "Original String From File: " << sBuffer << endl;

          cout << "Modified Str from File: " << fixed << setprecision(2) 
          << dValue << endl;
    }

    fgetc( stdin );
    return 0;
}      

所以它就像它应该的那样工作。但是我无法让它在 for 循环内工作,或者当我的文本文件中有多个字段时...

With this code, why is it taken off the decimal?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <sstream>
#include <errno.h>

using namespace std;

int main()
{
    string usrFileStr,
    myFileStr = "myFile.txt",  // declaring an obj string literal
    sBuffer, 
    sLine = "";


    istringstream inStream;

    int lineCount = 1;
    int nStart;
    double dValue = 0,
    dValue2 = 0;
    float fvalue;

    fstream inFile;                  // declaring a fstream obj
    // cout is the name of the output stream
    cout << "Enter a file: ";
    cin >> usrFileStr;


    inFile.open( usrFileStr.c_str(), ios::in ); 
    // at this point the file is open and we may parse the contents of it

    if ( !inFile )
    {
         cout << "Not Correct " << endl;
    }


    while ( getline ( inFile, sBuffer ) )
    {
          nStart = -1 ;

          for ( int x = nStart + 1; x < sBuffer.length(); x++ )
          {
              if ( sBuffer[ x ] == ',' )
              {
                   nStart = x;
                   break;
              }

              cout << sBuffer[ x ];
          }

          for ( int x = nStart + 1; x < sBuffer.length(); x++ )
          {

              if ( sBuffer[ x ] == ',' )
              {    
                   nStart = x;
                   break;
              }

              cout << sBuffer[ x ];
          }


          for ( int x = nStart + 1; x < sBuffer.length(); x++ )
          {   

              if ( sBuffer[ x ] == ',' )
              {
                   nStart = x;
                   break;
              }

              sLine = sBuffer[ x ];
              inStream.clear();
              inStream.str( sLine );

              if ( inStream >> dValue )
              cout << setprecision(1) << dValue;

          }


          for ( int x = nStart + 1; x < sBuffer.length(); x++ )
          {
              if ( sBuffer[ x ] == ',' )
              {
                   nStart = x;
                   break;
              }

              sLine = sBuffer[ x ];     
              inStream.clear();
              inStream.str( sLine );

              if ( inStream >> dValue2 )
                  cout << setprecision(1) << dValue2;    
          }

          cout << ") \n";
          lineCount++;
    }


    cout << "There are a Total of: " << lineCount -1 << " line(s) in the file."
    << endl;

    inFile.clear();           // clear the file of any errors
    inFile.close();  // at this point we are done with the file and may close it

    fgetc( stdin );
    return 0;
}

在第一个代码中我没有任何其他字符可以循环,因为我只是读取一个漂亮的小 double 值。

在我的第二个代码中,在我想要的那个之前我有很多字符要到达。但无论如何,它仍然与其他角色隔离开来,并且仍然处于自己的变量中。我很难意识到问题是什么:/尽管我认为它是 for 循环。

我也试过 atof,但我得到的是小数点所在的“0”。 strtod 很难,因为我不需要将数据读入 const char *cPtr

最佳答案

您的代码有点难读。您可能想考虑一些关于封装并将其分解为函数的问题。

此外,我会尽量避免读取单个字符并使用各种函数和方法来读取字段中的数据 - 您可以使用 >>> 流提取器读取整个 float 或整数.

最后,学习一个有用的技能是如何使用调试器。您可以逐步执行代码并检查变量的值。

也就是说,您的问题似乎出在这里:

          if ( sBuffer[ x ] == ',' )
          {
               nStart = x;
               break;
               }

          **** sLine = sBuffer[ x ];     
          inStream.clear();
          inStream.str( sLine );

          if ( inStream >> dValue2 )
          cout << setprecision(1) << dValue2;

在标有“****”的行中,您将一个字符恰好放入名为“sLine”的变量中。这样做之后,您将该字符转换为 double 变量 dValue2,然后将其输出。为什么要将这个字符转换为您想要的数字的第一位应该很明显。

关于c++ - StringStream 循环失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/478806/

有关c++ - StringStream 循环失败的更多相关文章

  1. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  5. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  8. ruby - 正则表达式在哪个位置失败? - 2

    我需要一个非常简单的字符串验证器来显示第一个符号与所需格式不对应的位置。我想使用正则表达式,但在这种情况下,我必须找到与表达式相对应的字符串停止的位置,但我找不到可以做到这一点的方法。(这一定是一种相当简单的方法……也许没有?)例如,如果我有正则表达式:/^Q+E+R+$/带字符串:"QQQQEEE2ER"期望的结果应该是7 最佳答案 一个想法:你可以做的是标记你的模式并用可选的嵌套捕获组编写它:^(Q+(E+(R+($)?)?)?)?然后你只需要计算你获得的捕获组的数量就可以知道正则表达式引擎在模式中停止的位置,你可以确定匹配结束

  9. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  10. ruby - 使用 rbenv 和 ruby​​-build 构建 ruby​​ 失败,出现 undefined symbol : SSLv2_method - 2

    我正在尝试在配备ARMv7处理器的SynologyDS215j上安装ruby​​2.2.4或2.3.0。我用了optware-ng安装gcc、make、openssl、openssl-dev和zlib。我根据README中的说明安装了rbenv(版本1.0.0-19-g29b4da7)和ruby​​-build插件。.这些是随optware-ng安装的软件包及其版本binutils-2.25.1-1gcc-5.3.0-6gconv-modules-2.21-3glibc-opt-2.21-4libc-dev-2.21-1libgmp-6.0.0a-1libmpc-1.0.2-1libm

随机推荐