如何修复功能,search_replace负数用'0'

问题描述 投票:1回答:1

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

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"
c file-io str-replace
1个回答
1
投票

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

我修改了你的代码。在我的作品中,我只有一面旗帜 - 我们是否正在读取负数?我在前面添加了一个窥视来处理一个不是数字的一部分的情况(“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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.