我正在编写一个程序,可以格式化包含数千行数据的文本文件。输入的文本文件是这样的行:
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/