用符号中的空格替换符号

时间:2015-02-20 18:58:02

标签: c++ string replace

我正在编写一个程序,可以格式化数千行数据的文本文件。输入文本文件是以下行:

  

2010-01-01 00:00:00 0.5203​​68 0.558565 0.567376

我想要做的是更换短划线和':'用空格,然后放入适当的标签。我想出了如何解决标签问题,但我的替换算法不起作用。任何帮助是极大的赞赏。我的代码目前看起来像这样:

void getReportInfo(ifstream& file, ofstream& ofile)
{
  string date, time;
  double wheight1, wheight2, wheight3;


         while(!file.eof())
         {
           file >> date >> time >> wheight1 >> wheight2 >> wheight3;

           //replace dashes 
           for(int i = 0; i < date.length(); i++) {
             if(date[i]== '-')
               date[i] == ' ';
           }
           ofile << date << " ";

           //replace colons
           for(int i = 0; i < time.length(); i++) {
             if(time[i]== ':')
               time[i] == ' ';
           }
           ofile << time << " ";

           ofile << "\t" << wheight1 << " \t" << wheight2 << " \t" << wheight3 << endl;
         }
}

3 个答案:

答案 0 :(得分:2)

首先,while(!file.eof())被认为是错误的。

  

我想要做的是用空格替换破折号和':',然后放入适当的标签。

如果您真的只是在用'.'替换'-'' '后,您应该有类似的内容

 std::string line;
 while(std::getline(file,line)) {
      std::replace(std::begin(line),std::end(line),'-',' ');
      std::replace(std::begin(line),std::end(line),'.',' ');
      ofile << line << std::endl;
 }

我不太确定,您认为正确的标签,但是line的第一次阅读,仍然可以帮助您解析您感兴趣的特定值。 您只需使用line

解析std::istringstream中的所需值
 std::istringstream iss(line);
 iss >> date >> time >> wheight1 >> wheight2 >> wheight3;

答案 1 :(得分:2)

使用replace标题中的<algorithm>

replace(begin(date), end(date), '-', ' ');
replace(begin(time), end(time), ':', ' ');

答案 2 :(得分:1)

C ++ 11 get_time / put_time实际上为您提供了更好的解决方案:

tm foo;

while (!file.eof())
{
    file >> get_time(&foo, "%Y-%m-%d %H:%M:%S") >> wheight1 >> wheight2 >> wheight3;
    ofile << put_time(&foo, "%Y %m %d %H %M %S") << "\t" << wheight1 << " \t" << wheight2 << " \t" << wheight3 << endl;
}

当然,您从其他帖子中了解到,您需要更好地处理循环条件。

另一个注意事项是gcc 4.9.2不支持get_time / put_time

最后一点,最好的方法是阅读此内容get_time(&foo, "%F %T"),但即使微软似乎也不支持:(

我知道您现在可能正在考虑put_time / get_time是一些粗略的回水解决方案,但我向您保证 犹太洁食C ++ 11。< / p>