[C語言!20點]改寫CODE:最長共同子序列

2009-03-31 7:00 am
這是luke大大寫的:求最長共同子序列

#include <stdio.h>
#include <string.h>
#define MAX_LEN 100

int main() {

char str1[MAX_LEN], str2[MAX_LEN], lcs[MAX_LEN] = {0};

char table[MAX_LEN + 1][MAX_LEN + 1][2] = {0};

int len1, len2, lcslen, i, j;


printf("Please input the first string: ");

scanf("%s", str1);


printf("Please input the second string: ");

scanf("%s", str2);


len1 = strlen(str1);

len2 = strlen(str2);


for(i = 1; i <= len1; i++) {

for(j = 1; j <= len2; j++) {

if(str1[i - 1] == str2[j - 1]) {

table[i][j][0] = table[i - 1][j - 1][0] + 1;

table[i][j][1] = 'P';

} else if(table[i - 1][j][0] >= table[i][j - 1][0]) {

table[i][j][0] = table[i - 1][j][0];

table[i][j][1] = 'U';

} else {

table[i][j][0] = table[i][j - 1][0];

table[i][j][1] = 'L';

}

}

}



i = len1; j = len2;

lcslen = table[i][j][0];



while(lcslen) {

switch(table[i][j][1]) {

case 'P':

lcs[--lcslen] = str1[i - 1];

i--; j--;

break;

case 'U':

i--;

break;

case 'L':

j--;

break;

}

}

printf("The longest common subsequence is: %s\n", lcs);

return 0;

}


我想改寫成讀檔的方式
(就是從input1.txt讀第一筆字串 從input2.txt讀第二筆字串)
(input1和input2裡面都各只有一行字串)
原本luke大大的code是可以執行的
可是改寫了後反而不能執行@_@
有大大可以幫忙一下嗎??
更新1:

這是我的寫法: file1=fopen("C:/input1.txt","r"); file2=fopen("C:/input2.txt","r"); fscanf(file1,"%s",str1); fscanf(file2,"%s",str2); fclose(file1); fclose(file2);

更新2:

跟大大您寫的差不多啊~@_@ (還是有我自己沒發現的錯誤??) 我只打算改成從檔案讀黨,最後還是依樣printf出來lcs 可是run出來就是說發生問題 然後直接關閉= =

更新3:

FILE *file1, *file2; 這個我有宣告啦 只是忘了po上來^^ 讀黨那邊改成"C:\input.txt"(打成C:/是我不小心打太快了哈哈) 也是錯誤 跑不出來耶>"

更新4:

我之前就試過了"input1.txt"...也是一樣錯誤~~

回答 (1)

2009-03-31 8:19 am
✔ 最佳答案
Change the following:
printf("Please input the first string: ");
scanf("%s", str1);

printf("Please input the second string: ");
scanf("%s", str2);

into:
FILE *f_ptr;

f_ptr = fopen("input1.txt", "r");
fscanf(f_ptr,"%s", str1);
fclose( f_ptr );

f_ptr = fopen("input2.txt", "r");
fscanf(f_ptr,"%s", str2);
fclose( f_ptr );

2009-03-31 22:33:35 補充:
Have you declared the file pointer?

FILE *file1, *file2;

2009-03-31 22:55:27 補充:
Also, for DOS environment, shouldn't your filename be c:\input1.txt not c:/input1.txt?

2009-04-01 08:14:18 補充:
I have tried that and it works fine. I am exceeding my 300 words limit and may not be able to post more. Post your program and e-mail me for my version.

2009-04-01 08:21:17 補充:
In my case, I put all files into the same directory as the one in the program and when I execute, I execute the program in the program's own directory. Note that I use "input1.txt" instead of "c:\input1.txt"


收錄日期: 2021-04-29 22:18:23
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090330000015KK11284

檢視 Wayback Machine 備份