2010-05-04 19 views
0

所以,感謝所有幫助人員,我只是有最後一個問題,我把網站源代碼放在char var中,然後閱讀產品標題(我有得到的),但它只適用於如果我參加的源代碼,或僅neweggs頁上的特色產品之一的HTML。我認爲這個程序崩潰了,因爲當我需要把所有三個標題放到一個數組中時,它不知道選擇哪個標題。有任何想法嗎?謝謝。下面是解析器代碼:C++,從網站獲取文本,第3部分

http://paste2.org/p/809045

任何溶液不勝感激。

/** 
* num_to_next - 
* takes in a pointer to a string and then counts how many 
* characters are until the next occurance of the specified character 
* @ptr: the pointer to a string in which to search 
* @c: char delimiter to search until 
**/ 


int num_to_next(char *ptr, char c) 
{ 
     unsigned int i = 0; 
     for (i = 0; i < strlen(ptr); i++) { 
       if (ptr[i] == c) { 
         return i; 
       } 
     } 
     return -1; 
} 


/** 
* space_to_underscore - 
* this should help to alleviate some problems when dealing with 
* filepaths that have spaces in them (basically just changes all 
* spaces in a string to underscores) 
* @string: the string to convert, yo 
**/ 


int space_to_underscore(char *string) 
{ 
     for (unsigned int i = 0; i < strlen(string); i++) { 
       if (string[i] == ' ') { 
         string[i] = '_'; 
       } 
     } 
     return 0; 
} 

char *file_name = (char *)malloc(sizeof(char *)); // allocate memory for where the app name will be stored 
memset(file_name, 0, sizeof(file_name)); // zero the memory 

char td_one[] = "<ul class="featureCells"><li id="ItemCell" class="cell">"; 

char *pstr = strstr(buffer, td_one) + strlen(td_one) + 6; // buffer is the source 

char *poop = pstr + num_to_next(pstr, '>') + 1; 

int blah = num_to_next(poop, '<'); 

strncpy(file_name, poop, blah); 

// null terminate the string // 
file_name[blah] = '\0'; 

space_to_underscore(file_name); 

MessageBox(NULL, file_name, "Product Name", MB_OK); 

free(file_name); 

回答

0

我不知道,如果這些是你唯一的問題,但...

首先,你不能這樣做char* filename = (char*)malloc(sizeof(char*))(當然,你可以,但是這不是你真正想從你的應用程序)。

你想要的是char* filename = (char*)malloc(SIZE_OF_YOUR_STRING * sizeof(char));,所以你不能爲你的字符串分配一個抽象緩衝區,你必須知道它的預期大小。實際上,在這裏你不必寫sizeof(char),因爲它總是等於1,但是有時候這種編寫代碼的方式可以幫助你(或者其他人)理解這個塊將字符串存儲爲字符數組)。

關於同一問題的另一個例子:char* filename = (char*)malloc(65); - 沒問題,並會分配一塊內存來存儲65個字符符號。

如果我們進一步去(你正在做的memset),char*是一個普通的指針,你的情況會回到你的指針的大小sizeof(filename),但不是你的。你應該寫的是strlen(filename)