用字符串中的空格替换符号

Replacing symbols with spaces in a string

本文关键字:替换 符号 空格 字符串      更新时间:2023-10-16

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

2010年01月01日00:00:00 0.520368 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;
         }
}

首先,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,仍然可以很好地解析您感兴趣的特定值。您只需使用std::istringstream:从line解析所需的值

 std::istringstream iss(line);
 iss >> date >> time >> wheight1 >> wheight2 >> wheight3;

使用<algorithm>标头中的replace

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

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。