[英]Segmentation fault, 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
}
這是我使用scanf的方法造成的嗎?
除了將地址傳遞給scanf
(scanf("%i",&sa)
,這是您必須要做的(檢查地址的返回值也是正確的)-您需要更正以下幾項:
應該是(value = fscanf(oIfile, "%c", value)) != EOF
。 !=
優先級比=
因此需要此優先級才能獲得正確的結果。
同樣, a[(i+sa)%62]=...
是正確的處理方式。 因為否則,它將對某些sa
值超出范圍訪問數組索引,從而導致未定義的行為。
fprintf(stream,"%c",charvariable)
這將用於fprintf
。
該value
被fscanf
返回的value
所覆蓋的value
覆蓋。 您應該使用其他臨時變量,甚至更好地使用while(fscanf(oIfile, "%c", value)!=EOF)
。 但是要進行更多檢查,您需要像
int c; while((c=fscanf(oIfile, "%c", value))!=EOF)
您可以通過傳遞的價值在這里得到了分段故障sa
中,而不是它的地址scanf
。
scanf
將地址作為參數。 嘗試這個;
scanf("%i", &sa);//Get shift
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.