0
我正在編寫一個程序,當用戶輸入月份和日期編號時,將輸出月份和年份日期。預期的輸入和輸出如下。c:帶支柱和陣列的字符串輸入
Enter month and day number? december 30
December (DEC) 31 means 364 days YTD.
我的程序沒有編譯,我使用的是Microsoft Visual Studio。使用與預期輸入相同的輸入我試圖運行程序;但是,輸入月份和日期編號後,程序崩潰。從編譯器
警告:
'scanf_s' : format string '%s' requires an argument of type 'unsigned int', but variadic argument 2 has type 'int *'
'scanf_s' : not enough arguments passed for format string
當我使用調試器,我輸入的月份和日期後,然後進行單步執行代碼程序給出了這些消息。它似乎沒有足夠的內存來繼續?如果這是問題,解決問題的最合理的方法是什麼?
Exception thrown at 0x0FCA0BA9 (ucrtbased.dll) in lab14program345words.exe: 0xC0000005: Access violation writing location 0x003C0000.
下面是我的代碼:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int finddata(int month, int days);
struct month
{
char name[10];
char abbrev[4];
int days;
int monumb;
};
int main()
{
struct month months[12] =
{
{ "January", "jan", 31, 1 },
{ "February", "feb", 28, 2 },
{ "March", "mar", 31, 3 },
{ "April", "apr", 30, 4 },
{ "May", "may", 31, 5 },
{ "June", "jun", 30, 6 },
{ "July", "jul", 31, 7 },
{ "August", "aug", 31, 8 },
{ "September", "sep", 30, 9 },
{ "October", "oct", 31, 10 },
{ "November", "nov", 30, 11 },
{ "December", "dec", 31, 12 }
};
struct month userdata;
int i = 0;
int total;
do
{
printf("Enter month and day number:");
scanf_s("%s %d", userdata.name, &userdata.days); //line 42, where the warnings occur
toupper(userdata.name[0]);
if (strcmp(userdata.name, months[i].name) == 0) // should compare user's entered month to months in month montths array
{
puts(months[i].name);
puts(months[i].abbrev);
}
else
{
i++;
}
total = finddata(months[i].monumb, userdata.days); // should pass the month number and days the user entered.
printf("%d days YTD.\n", total);
} while ((userdata.monumb > 0) || (userdata.monumb < 13));
return 0;
}
int finddata(int months, int days)
{
int total = 0;
if (months == 1)
{
total = days;
}
else if (months == 2)
{
total = days + 31;
}
else if (months == 3)
{
total = 31 + 28 + days;
}
else if (months == 4)
{
total = 31 + 28 + 31 + days;
}
else if (months == 5)
{
total = 31 + 28 + 31 + 30 + days;
}
else if (months == 6)
{
total = 31 + 28 + 31 + 30 + 31 + days;
}
else if (months == 7)
{
total = (31 * 3) + 28 + (30 * 2) + days;
}
else if (months == 8)
{
total = (31 * 4) + 28 + (30 * 2) + days;
}
else if (months == 9)
{
total = (31 * 5) + 28 + (30 * 2) + days;
}
else if (months == 10)
{
total = (31 * 5) + 28 + (30 * 3) + days;
}
else if (months == 11)
{
total = (31 * 6) + 28 + (30 * 3) + days;
}
else if (months == 12)
{
total = (31 * 6) + 28 + (30 * 4) + days;
}
else
{
//blank
}
return total;
}
這有助於,謝謝。 – Markovnikov
@Markovnikov很高興幫助! – ameyCU
「在%c的情況下,您需要傳遞1」 - >它不需要像'(rsize_t)sizeof userdata.name'那樣是'(rsize_t)1'。 OTOH如果'1'確定,那麼'(unsigned)sizeof userdata.name'應該是OK。類型要求對於'「%s」'和'「%c」'的大小參數肯定是一樣的。我懷疑鏈接的引用和C規範在這一點上略有不同。 – chux