用字符串中的空格替换符号
Replacing symbols with spaces in a string
我正在编写一个程序,可以格式化数千行数据的文本文件。输入文本文件是行,例如:
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。
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 用符号版本替换对函数的所有调用
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在给定文本中用字符数组替换符号
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- 在编译时替换对象文件中的符号.例如,换掉main
- LD_PRELOAD应该加载模块还是只使用模块来替换符号
- 用字符串中的空格替换符号
- 使用指针将输入中的空格替换为破折号符号
- 如何查找字符串中的所有字符并将其替换为特定符号C++
- 将符号替换为表达式中的值并打印表达式输出
- 将 const 无符号字符* 分配给执行就地替换或省略的 std::string
- 如何有效地替换C++中的德语变音符号
- 是否可以用CMake将某个符号替换为不同的符号
- 链接器用内存地址替换符号引用
- 将正有符号变量替换为无符号变量
- 当一个符号替换几个符号时,是否存在从UTF-8到CP1251的音译?