我正在尝试清除数据文件中具有某些条件的特殊字符,但这些条件不满足
I am trying to clean my data file from special characters with some conditions, but those conditions are not met?
这是我的代码
此代码试图从.txt文件中删除特殊字符,如",',{,},(,),并将其替换为空格。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <iostream>
#include <time.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
int fd;
int i;
int j;
int len;
int count = 0;
int countcoma = 0;
int countquote = 0;
char buf[10];
char spec[] = {',','"',':','{','}','(',')','''};
fd = open(argv[1],O_RDWR,0777);
while (read(fd,buf,10) != 0) {
len = strlen(buf);
for (i=0;i<len;i++) {
for (j=0;j<8;j++) {
if (buf[i]==spec[j]) {
count =1;
countquote=0;
if (j==1) {
if (countcoma == 0) {
countcoma++;
}
if (countcoma == 1) {
countcoma--;
}
}
if ((j==7) && (countcoma ==1)) {
countquote = 1;
}
break;
}
}
//cout<<countquote;
if ((count != 0) && (countquote == 0)) {
buf[i] = ' ';
}
count = 0;
}
lseek(fd, -sizeof(buf), SEEK_CUR);
write(fd,buf,sizeof(buf));
memset(buf,' ',10);
}
return 0;
}
现在,我希望文件中双引号内的单引号保持不变,但所有特殊字符都用代码中提到的空格替换。我希望这些单引号保持不变,但在我运行文件后,它变成了Whats,而不是
了解regex和其他库。(当使用UNIX类型man regex
时。)现在您不必再编写代码了,有无数的库可以为您完成这项工作。
好的,所以代码的问题是你在做一件事,然后在下一节中撤消。特别是:
if (countcoma == 0) {
countcoma++;
}
if (countcoma == 1) {
countcoma--;
}
遵循逻辑:我们将countcoma
作为零。所以第一个if
是真的,并且它被递增。现在是1
。接下来,如果说if (countcoma == 1)
,那么现在它是真的,我们递减它。
我用countcoma = !countcoma;
代替了它,这是一种更简单的方式,可以说"如果它是0,就把它变成1,如果它是1,就让它变成0 . You could put an
,否则就是on the back of the first
,如果"来做同样的事情
还有一大堆风格上的东西:例如,硬编码的常量,写回原始文件(意味着如果有错误,你会丢失原始文件——幸好我没有用我的示例文件关闭编辑器窗口…),包括头文件中的一半空间,以及根据索引确定spec
字符中的哪个字符。
在我看来,您的代码正遭受一个比以前指出的更普遍的缺陷:
char buf[10]; /* Buffer is un-initialized here!! */
while (read(fd,buf,10) != 0) { /* read up to 10 bytes */
len = strlen(buf); /* What happens here if no byte was read? */
...
lseek(fd, -sizeof(buf), SEEK_CUR); /* skip sizeof(buf) = 10 bytes anyway */
write(fd,buf,sizeof(buf)); /* write sizeof(buf) = 10 bytes anyway */
memset(buf,' ',10); /* initialize buf to contain all spaces
but no , so strlen will still result in
reading past the array bounds */
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 转换特殊字符(UTF-8)
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何在C++中打印此"█"特殊字符?
- c++为什么ifstream get()函数返回无法识别的特殊字符
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 转义std::字符串中的特殊字符
- SDL2加载具有特殊字符的文件
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 如何从文本文件C++读取整数和特殊字符
- USB序列号显示特殊字符
- 键入特殊字符并保存在文件中
- 回文,不包括特殊字符和空格
- 无法使用 Unicode 特殊字符设置窗口文本
- 使用 libmysql 插入特殊字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 如何输入以特殊字符开头的字符串
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- C++降低特殊字符,例如 ü
- 我正在尝试清除数据文件中具有某些条件的特殊字符,但这些条件不满足