[英]Unknow error using strtok() inside strcpy()
我正在嘗試使用strtok()
從輸入中刪除換行符,並使用strcpy()
將其傳遞給 struct 屬性,但是當我執行此操作時,Visual Studio Code 返回此消息:
我的代碼:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#include <locale.h>
typedef struct
{
char name[50];
char document[50];
char cep[50];
char phone[50];
char address[50];
char birthdate[50];
char email[50];
char diagnosticDate[50];
int age;
char comorbidities[50];
} Ocurrence;
void insert_new_record()
{
Ocurrence new_record;
char comorbity_option[3];
printf("Choose option number: ");
fgets(&comorbity_option, sizeof(comorbity_option), stdin);
switch (comorbity_option[0])
{
case '1':
strcpy(new_record.comorbidities, "Diabetes");
break;
case '2':
strcpy(new_record.comorbidities, "Obesidade");
break;
case '3':
strcpy(new_record.comorbidities, "Hipertensão");
break;
case '4':
strcpy(new_record.comorbidities, "Tuberculose");
break;
case '5':
strcpy(new_record.comorbidities, "Outros");
break;
default:
strcpy(new_record.comorbidities, "Nenhuma");
break;
}
strcpy(new_record.name, strtok(new_record.name, "\n"));
strcpy(new_record.cep, strtok(new_record.cep, "\n"));
strcpy(new_record.address, strtok(new_record.address, "\n"));
strcpy(new_record.phone, strtok(new_record.phone, "\n"));
strcpy(new_record.birthdate, strtok(new_record.birthdate, "\n"));
strcpy(new_record.diagnosticDate, strtok(new_record.diagnosticDate, "\n"));
strcpy(new_record.document, strtok(new_record.document, "\n"));
strcpy(new_record.email, strtok(new_record.email, "\n"));
}
int main()
{
setlocale(LC_ALL, "Portuguese");
show_login();
show_menu();
return 0;
}
在調試模式下,可以驗證以下行后是否顯示錯誤: strcpy(new_record.name, strtok(new_record.name, "\\n"));
我在 StackOverflow 上搜索過這個,但任何東西都有助於解決這個問題。 有人可以幫助我嗎?
strcpy()
函數的前提條件是源字符串和目標字符串不重疊。 strtok()
通過就地修改輸入字符串來標記化,因此所有strcpy()
調用都違反了該前提條件。 但無論如何,您都不需要strcpy()
,因為strtok()
確實修改了輸入字符串。 只需執行strtok()
就足夠了。 例如:
strtok(new_record.name, "\n");
但是使用strcspn()
會更清楚,因為它明確表示意圖是修改字符串:
new_record.name[strcspn(new_record.name, "\n")] = '\0';
只要輸入字符串正確終止,無論輸入字符串是否包含換行符都是安全的。
然而,說到字符串終止,這是所呈現代碼的一個主要問題。 更一般地說,未能初始化您的字符串是一個重大問題。 出現在塊范圍內,這...
Ocurrence new_record;
... 不初始化new_record
或其任何成員。 之后的代碼確實在(的初始字節) new_record.comorbidities
中設置了一個值,但是當程序到達您的strcpy()
調用時,所有其他成員都保留完全不確定的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.