c++ - 用字符串中的空格替换符号

标签 c++ string replace

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

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())被认为是错误的。

What I want to do is replace the dashes and ':' with spaces, and then put proper tabs in.

如果你真的只是在将 '.''-' 替换为 ' ' 之后你应该有类似的东西

 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;
 }

我不是很确定,您认为什么是适当的制表符,但是第一次阅读,仍然可以很好地解析您感兴趣的特定值在。 您只需使用 std::istringstream 解析 line 中需要的值:

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

关于c++ - 用字符串中的空格替换符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636256/

相关文章:

c++ - C++中的类成为容器的条件是什么?

c++ - 想要平滑 opencv 中的 cv::Mat

C++ DLL 可以通知调用程序它的进度

c++ - 您可以在 CRTP 方法中对派生类使用约束吗?

c++ - 无法将值存储到 vector 结构中

mysql - 通过 strlen 从数据库中选择行

c++ - C++ 函数内定义的字符串变量是否需要释放内存?

javascript - 替换希腊数字格式 (1.000,00)

regex - 从字符串中删除非数字和非字母字符?

c# - 替换C#中所有目录和文件的名称