首页 > 解决方案 > 如果语句未检测到空字符串

问题描述

我有一个从标准输入获取用户输入的 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;
}

标签: cstringvalidationif-statement

解决方案


问题是 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 进行编译,这是一个常见的警告。


推荐阅读