我試圖用結構和文件做一個程序。以下是我的代碼的一部分(它不是整個程序)。 我想要做的是:讓用戶寫他的命令。例如。刪除約翰 例如。輸入John James 5000 ipad購買。構造,strtok,分段錯誤
問題是我想拆分命令爲了保存它的'args'爲一個struct元素。這就是我使用strtok的原因。但是我正在面臨另一個問題,那就是誰在結構上「放置」這些問題。 此外,我似乎很奇怪如何以安全的方式將'args''傳遞'到結構中,因爲我將所有輸入(來自用戶)保存在二進制文件中,可能會重新打開並重新編輯,因此我無法使用:
strcpy(catalog[0]->short_name, args[1]);
因爲是時候短名稱將被保存在結構的第一個元素中。但是,如果文件被寫入會發生什麼呢?第一個元素存在,所以如果我寫.. [0]我會寫上它? 我該怎麼辦?提前感謝任何幫助! :d
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char command[1500];
struct catalogue
{
char short_name[50];
char surname[50];
signed int amount;
char description[1000];
}*catalog[MAX];
int main (int argc, char *argv[])
{
int i,n;
char choice[3];
printf(">sort1: Print savings sorted by surname\n");
printf(">sort2: Print savings sorted by amount\n");
printf(">search+name:Print savings of each name searched\n");
printf(">delete+full_name+amount: Erase saving\n");
printf(">enter+full_name+amount+description: Enter saving \n");
printf(">quit: Update + EXIT program.\n");
printf("Choose your selection:\n>");
gets(command); //it save the whole command
/*in choice it;s saved only the first 2 letters(needed for menu choice again)*/
strncpy(choice,command,2);
choice[2]='\0';
char** args = (char**)malloc(strlen(command)*sizeof(char*));
memset(args, 0, sizeof(char*)*strlen(command));
char* temp = strtok(command, " \t");
for (n = 0; temp != NULL; ++n)
{
args[n] = strdup(temp);
temp = strtok(NULL, " \t");
printf(" %s ",args[n]);
}
strcpy(catalog[0]->short_name, args[1]); //segmentation fault
strcpy(catalog[0]->surname,args[2]);
catalog[0]->amount=atoi(args[3]); //atoi doesn't work
strcpy(catalog[0]->description,args[4]);
}
結果,運行該程序後,我收到了分割錯誤... 爲線:
strcpy(catalog[0]->short_name, args[1]);
任何幫助嗎?有任何想法嗎?
我不是C程序員,但對於您的問題標題,有些人不喜歡說「help plz」的人:http://meta.stackexchange.com/questions/48024/what-is- up-with-everyone-always-saying-plz-help – 2010-05-14 13:19:42
;)okkkk!hehehe thnx Andrew – FILIaS 2010-05-14 13:27:27