在文件中搜索 printf 语句并替换为字符串值
search printf statement in file and replace with string value
我正在尝试用字符串值替换所有printf
语句。所以首先,我将所有行读取为一个字符串,如下所示:
ifstream ifs;
ifs.open(filename);
string temp;
string text;
while(!ifs.eof())
{
getline(ifs, temp, 't');
text.append(temp);
temp.clear();
}
然后我找到printf
的每一行,如果找到,则用"printf statement"
替换它. 我替换printf
的代码:
char ch;
while(getline(is,check))
{
ch=check[0];
if(!isalpha(ch))
{
//statements..
}
else
{
string str2("printf");
size_t found;
found=check.find(str2);
if(found!=string::npos)
check="n printf statement.n";
OriginalStr.append(check);
check.clear();
}
它适用于三个四行文件,如下所示:
main()
{
Hi i am Adityaram.
and i am good boy.
and you?
printf("");
{
printf("");
Aditya
printf("");
Rammm
printf("");
Kumar
printf("");
{
printf("");
printf("");
}
printf("");
}
printf("");
但在这些文件行中找不到 printf 行。
main()
{
char ch, file_name[25],*p;
char answer[400];
int size=0;
FILE *fp;
printf("Enter the name of file you wish to see ");
gets(file_name);
}
为什么找不到printf行?或者怎么做?任何建议将不胜感激。
由于这是一个 C 程序,因此您可能有以下行:
{
或
}
即打开/关闭一个块。这绝对不是空的,但它将只包含 1 个字符。在你的while i<6
你在这个缓冲区结束后走得很远。因此,在此处添加检查i
小于缓冲区的长度。
然后,printf 不一定是该行中的第一个表达式,例如:
if(something) printf("this");
您的代码没有拾取此内容。您需要检查"printf"作为wd
中的子字符串。查看 http://www.cplusplus.com/reference/string/string/find/以获取有关在字符串中查找字符串的参考。
最后但并非最不重要的一点是,我不明白为什么您希望您的行以字母开头(检查 isalpha)。这将无法更改代码,例如
{ printf("this"); }
它适用于小型测试文件的原因是,您编写它们很可能是为了通过内部"测试",但大文件通常包含更广泛使用的 printf。
此外,缩进不是强制性的,使用制表符 (\t) 可能是简单的空格。
我明白了,通过这个简单的方式:
string RemovePrintf(string value)
{
string RemovedPrintf,strP;
size_t poss;
value.insert(0," ");//insert a white-space, cause find method not returning position if it present at begin of string.
poss = value.find("printf"); // position of "printf" in str
strP = ""; // get insert whitespace at "printf line".
strP.resize(strP.length());
if((int)poss > 0)
RemovedPrintf.append(strP);
else
RemovedPrintf.append(value);
strP.clear();
RemovedPrintf.resize(RemovedPrintf.length());
return RemovedPrintf;
}
这适用于小文件和大文件。顺便说一下,感谢您回答我的问题。
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 删除/替换C++字符串中的多字符 (ÿû)
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 用 X 替换字符串中的字符C++练习
- 从字符串 C++ 向量中替换字符串
- 替换字符串C++标点符号
- 有没有办法用参数替换字符串,例如 C++ 中的 printf
- 用递增的数字替换字符串中的空格
- 如何用双C 替换字符串的一部分
- 一种在视图中用 ID 替换字符串的简单方法
- 替换字符串C++中无效的XML unicode序列
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- 如何在C++中用"*"替换字符串中的字符?
- 是否有一种方法可以将变量列表传递给#Define指令,并导致其通过文字值替换字符串值
- G++ 和 boost 中 regex_replace() 替换字符串中''的不同处理方式
- 使用提升C++通过正则表达式替换字符串
- 创建一个函数来替换字符串中的某些字母
- 替换字符串中的3个或更多字符出现
- 替换字符串中空格的策略