分段错误,scanf

Kar*_*sir 1 c scanf

我们有一个赋值,即从文件中获取字符,将给定值向右移动(它在代码中有意义),然后将新值存储在新文件中,但我似乎遇到了分段错误,据我所知,这意味着我正在尝试访问我已分配的内存之外的内存?我是C的新手,我设法调试此代码直到这一点,老实说,我不知道该去哪里.我甚至不太明白这个问题是什么.

#include<stdio.h>
//Get Shift amount
//Get ifilename
//Get ofilename
//open them
//Get characters one at a time from input
//Process and shift by shift amount
int main()
{
    int i;//loop value
    char a[62]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//Variable with every value
    int sa = 0;//Store Shift value
    char ofile[30];//contain the name of output file
    char ifile[30];//contain name of input file
    char value;//Value to keep the current value in

    printf("How far in ascii values would you like to shift?\n");
    scanf("%i", sa);//Get shift
    printf("What is the name of your input file located in this directory?");
    scanf("%s", ifile);//get input name
    printf("What would you like to name your new file?\n Do note that it will overwrite the current file named this!");
    scanf("%s", ofile);//Get output name

    FILE *oIfile = fopen(ifile, "r"), *oOfile = fopen(ofile, "w");

    while(value = fscanf(oIfile, "%c", value) != EOF)//Check to ensure that you never reach the end of the file
    {
        for(i=0; i<62; i++)//loop through the list of all characters
        {
            if(value == a[i])//check to see if the value from the input file matches with which letter
            {
                value = a[i+sa] % 62;//incrase the value by the shift amount, check if its longer than 62, add remainder
                break;//break the for loop so we can restart the while loop with the next letter
            }
        }
        fprintf(oOfile, "%c");//print the new value to the output file
    }
    fclose(oIfile);//close input file
    fclose(oOfile);//close output file
}
Run Code Online (Sandbox Code Playgroud)

这个问题是由于我对scanf的态度?

use*_*738 5

除了传递scanf (scanf("%i",&sa)你将要做的地址(也检查它的返回值是正确的) - 你需要纠正一些事情: -

  • 它应该是(value = fscanf(oIfile, "%c", value)) != EOF.!=具有更高的优先级,=因此需要获得正确的结果.

  • 也是a[(i+sa)%62]=...正确的做事方式.因为否则它将访问数组索引超出某些sa导致未定义行为的值.

  • fprintf(stream,"%c",charvariable)这将是用途fprintf.

  • value是在写有正在该值返回什么fscanf回报.您应该使用其他临时变量,甚至更好,只需这样做while(fscanf(oIfile, "%c", value)!=EOF).但要进行更多检查,你需要做些什么

      int c;
      while((c=fscanf(oIfile, "%c", value))!=EOF)
    
    Run Code Online (Sandbox Code Playgroud)

这里通过传递值sa而不是其地址来获得分段错误scanf.