如何修复函数,将search_replace负数替换为'0'

时间:2019-04-01 19:04:33

标签: c file-io str-replace

我想创建一个函数,该函数在文本文件中进行搜索,并将负数(无论多长时间)替换为零,然后将数字粘贴到字母上,某些情况下将符号粘在字母上,并且它们不在单独的行上

They idea I had is to create an array and check if there is a match after I find a - sing, if there is I use a for loop to get all the numbers after the - into a (dead-end) if you could say that. I think for the most part I am on the right track, but I just don't know how to execute it.

void change_negative_numbers(FILE *fp_in, FILE *fp_out)//function
{
    int flag1 = false; // flag for checking 
    int flag2 = false; // flag for checking
    char searched_s[10] = {'0','1','2','3','4','5','6','7','8','9'}; // array to match searching
    char ch; // to save character by char.

    while ((ch = fgetc(fp_in)) != EOF) // till end of file
    {
        if (ch == '-')
        {
            flag1 = true; // finding minus
        }

        else if (flag1 == false) // if there is no negative number
        {
            fputc(ch,fp_out); // print if not
        }

        if (ch == searched_s && flag1 == true) // if flag1 = 1;
        {
            for (; ch == searched_s; ch++) //dead end
            {

            }
                    fprintf(fp_out,"0"); //prints 0 in place of negative number in theory
            flag1 = false; //normalize flag
        }

    }

}

    //Input: "hhh ddd -55ttt uuuhhh6666"

    //Expected output: "hhh ddd 0ttt uuuhhh6666"

    //Actual output: "hhh ddd"

1 个答案:

答案 0 :(得分:1)

ch == searched_s不是有效的比较,因为一个是char而一个是char数组。您可以使用isdigit()测试字符是否为数字。

我已经修改了您的代码。在我的手中,我只有一个标志-我们正在读取负数吗?我在前面加了个速览,以处理其中的破折号不属于数字(“ hello-there”)的情况。

void change_negative_numbers(FILE *fp_in, FILE *fp_out)//function
{
    int in_number = false; // flag for checking 
    int ch; // Changed to int since EOF is

    while ((ch = fgetc(fp_in)) != EOF)
    {
        // Check for '-' followed by digit
        if (ch == '-')
        {
            // Peek ahead
            ch = fgetc(fp_in);
            if (isdigit(ch)) {
                // It is a number. Write 0 and set flag
                fputc('0', fp_out);
                in_number = true;
            }
            else {
                // Not a number write back '-' and peeked char
                fputc('-', fp_out);
                if (EOF != ch) fputc(ch, fp_out);
                in_number = false;
            }
        }
        // Only write non-digits or when not reading a negative number
        else if (!isdigit(ch) || !in_number) {
            fputc(ch, fp_out);
            in_number = false;
        }
    }
}