c - 要更换更好的方法 [英] C - Better method for replacing

查看:86
本文介绍了c - 要更换更好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在那里words.txt包含香蕉苹果测试将输出文件进行替换 - >香蕉苹果代替!这将是寻找替代会来作为参数传递给标准输入的词(试验,在这种情况下)

不知道在我的code会错的,我也想知道是否有更好的方法来做到这一点比得到的getchar()函数,因为我觉得它混淆一起工作,和恼人的,因为你不能备份的字符。

有什么建议?谢谢

  $ ./a.exe测试< words.txt
    #包括LT&;&stdio.h中GT;
    #包括LT&;&stdlib.h中GT;
    #包括LT&;&string.h中GT;    INT主(INT ARGC,字符** argv的){
        INT C =的getchar();
        INT计数器= 0;
        INT I,指数;
        对于(i = 1; I< ARGC,我++){
            对于(指数= 0;指数 - LT;的strlen(argv的[I]);指数++){
                而(C = =的argv [I] [指数]){
                    反++;
                    C =的getchar();
                    指数++;
                    如果(反== strlen的(的argv [I])){
                        的printf(所取代!);
                    }
                }
                的printf(%C,C);
                C =的getchar();
                计数器= 0;
            }
        }
        返回(0);
    }


解决方案

我想如下做到这一点:


  1. 阅读所有的文件到使用缓存与fgets

  2. 寻找使用重点工作(测试)的strstr

  3. 与新字符串使用替换函数strncpy

  4. 写入文件(或输出到标准输出)任何你想做的事

I'm looking to replace words from a file where words.txt contains "banana test apple" would output -> "banana Replaced! apple" The words it would be looking to replace would come as an argument to stdin ("test" in this case)

Not sure where my code is going wrong, and I'm also wondering if there's a better way to do it than get getchar() function, as I find it confusing to work with, and annoying as you cannot backup characters.

Any suggestions? Thanks

    $ ./a.exe test < words.txt


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main(int argc, char** argv) { 
        int c = getchar();    
        int counter = 0;


        int i,index;
        for (i = 1; i < argc; i++){
            for (index = 0; index < strlen(argv[i]); index++){
                while (c == argv[i][index]){
                    counter++;
                    c = getchar();
                    index++;
                    if (counter == strlen(argv[i])){
                        printf("Replaced!");
                    }
                }
                printf("%c ",c);
                c = getchar();
                counter = 0;
            }
        }
        return (0);
    }

解决方案

I would do it as follows :

  1. read all the file into a buffer using fgets
  2. looking for the key work (test) using strstr
  3. replace it with your new string using strncpy
  4. write to file (or output to stdout) whatever you want to do

这篇关于c - 要更换更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆