如何在visual c ++中比较字符串变量和常量字符串?

时间:2014-01-20 20:18:07

标签: visual-c++ strcmp

我有这段代码:

#include "stdafx.h"
#include "afx.h"
...

char * connectionType;
...

int readParameters() {

    ...
    //hFile is a file handler previously initialized
    result = readParameter(hFile, connectionType);
    if (strcmp(connectionType, "3") == 0) {
        //do something
    } else {
        //do other thing
    }
    ...
}

int readParameter(HANDLE hFile, OUT char * buffer) {
   BOOL bResult = true;
   BOOL continueLine = true;
   char inBuffer[1];
   DWORD bytesToRead = 1;
   DWORD bytesRead = 0;
   OVERLAPPED stOverlapped = {0};

   char parameter[256] = {};
   int counter = 0;

   while (continueLine) {
       bResult = ReadFile(hFile, inBuffer, sizeof(char), &bytesRead, &stOverlapped);
       if (!bResult) {
       return 0;
       } else if (inBuffer[0] == '\n' || bytesRead == 0) {
           continueLine = false;
   } else {
            parameter[counter] = inBuffer[0];
            counter++;
            if (bResult && bytesRead == 0) {
                continueLinea = false;
            }
        }
    }

    parameter[counter] = '\0';
    memcpy(buffer, parameter, 256);

    return 1; 
}

通过调试,我知道 connectionType 属性最终是以空终止的字符串“3”,但 strcmp 方法保持返回3328(> 0)。有问题因为“3”是常数吗?可能是什么问题?

1 个答案:

答案 0 :(得分:0)

我意识到代码的问题是什么。问题是 connectionType ,其值为空终止字符串“3”,实际上与从文件读取的行不同,实际上是“3”加上回车符加上空。

在我对代码添加了这个考虑之后,我的问题就解决了。