c - 如果语句未检测到空字符串
问题描述
我有一个从标准输入获取用户输入的 C 应用程序。我有一个验证功能,它应该检测用户何时按下ENTER
而不向控制台写入任何内容。我试过if (strSurveyDate[0] == "")
and if (strcmp(strSurveyDate[0], "") == 0)
,但那些不起作用。第一个根本不执行(显然不满足条件),第二个给出access violation reading location 0x00000000
错误。我有一个Trim()
函数可以在将输入发送到函数进行验证之前去掉前导和尾随空格,所以我不能简单地查找\n
,\r
等等。我已经逐步完成了代码,并且""
是发送到函数的内容。
我不确定是否需要包含更多代码,但我会的。这是整个验证功能:
int ValidateSurveyDate(char strSurveyDate[])
{
// declare variables
int intTrue = 1;
int intFalse = 0;
// validate that input was entered
if (strcmp(strSurveyDate[0], "") == 0)
{
printf("ERROR: Please enter a survey date.\n");
return intFalse;
}
else { return intTrue; }
}
这是我获取用户输入并将其发送到验证函数的代码:
printf("Please enter the date of the survey.\n");
fgets(strSurveyDate, sizeof(strSurveyDate), stdin);
Trim(strSurveyDate);
// validate date of survey
if (ValidateSurveyDate(strSurveyDate) == 1)
如果我需要包含其他任何内容,请告诉我,我很乐意将其包含在内。感谢您的帮助,我真的很感激。
根据要求,这是Trim()
功能:
void Trim(char strSource[])
{
int intIndex = 0;
int intFirstNonWhitespaceIndex = -1;
int intLastNonWhitespaceIndex = 0;
int intSourceIndex = 0;
int intDestinationIndex = 0;
// Default first non-whitespace character index to end of string in case string is all whitespace
intFirstNonWhitespaceIndex = StringLength(strSource);
// Find first non-whitespace character
while (strSource[intIndex] != 0)
{
// Non-whitespace character?
if (IsWhiteSpace(strSource[intIndex]) == 0)
{
// Yes, save the index
intFirstNonWhitespaceIndex = intIndex;
// Stop searching!
break;
}
// Next character
intIndex += 1;
}
// Find the last non-whitespace character
while (strSource[intIndex] != 0)
{
// Non-whitespace character?
if (IsWhiteSpace(strSource[intIndex]) == 0)
{
// Yes, save the index
intLastNonWhitespaceIndex = intIndex;
}
// Next character
intIndex += 1;
}
// Any non-whitepsace characters?
if (intFirstNonWhitespaceIndex >= 0)
{
// Yes, copy everything in between
for (intSourceIndex = intFirstNonWhitespaceIndex; intSourceIndex <= intLastNonWhitespaceIndex; intSourceIndex += 1)
{
// Copy next character
strSource[intDestinationIndex] = strSource[intSourceIndex];
intDestinationIndex += 1;
}
}
// Terminate
strSource[intDestinationIndex] = 0;
}
解决方案
问题是 strSurveyDate[0] 是一个字符而不是一个要比较的字符串。
尝试这个:
int ValidateSurveyDate(char *strSurveyDate){
// declare variables
int intTrue = 1;
int intFalse = 0;
// validate that input was entered
if (!strcmp(strSurveyDate, "")){
printf("ERROR: Please enter a survey date.\n");
return intFalse;
}else{
return intTrue;
}
}
正如 Siguza 所述,始终使用 -Wall 进行编译,这是一个常见的警告。
推荐阅读
- r - 列表列中的 data.table 行比较
- c# - 通过 APIGEE 运行时 Swagger 不起作用
- php - PHP用另一个字符串中的单词替换字符串
- angular - 从子组件向表单添加输入
- javascript - Javascript函数立即停止
- android - 使用 Android Canvas.drawCircle() 时如何在画布上制作圆形动画
- angular - Angular4 在超时时重播我的请求
- python-3.x - Python中今天日期和负3个月之间的条件语句
- java - Spring webflux:如何配置 Controller 和 WebClient 像代理一样工作?
- php - 语言子文件夹上的 htaccess 404 错误(en/)