仅比较数组中的一个char

Adn*_*bir -1 c++ c++14

我是C的新人

这是我的代码

#include <iostream>
#include <string.h>
using namespace std;

int main() {
char time[20];
       scanf("%s",time);

       // command and "hello" can be less than, equal or greater than!
       // thus, strcmp return 3 possible values
       if (strcmp(time, "PM") == 0)
       {
          printf("It's PM \n");
       }


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

假设我在下午12:13:14输入

我想知道它是上午还是下午.但上面的代码只发现整个char数组是否为"PM".我看过其他帖子,我无法理解它们.

Som*_*ken 5

strcmp检查整个字符串是否相等,以检查子字符串的使用strstr:

if (strstr(time, "PM") != NULL)
  printf("It\'s PM \n");
Run Code Online (Sandbox Code Playgroud)

旁注,仅为您的输入保留20个字符可能会很麻烦.


此外,您的代码看起来像C++而不是C,如果是这种情况使用cin,std::string而是:

std::string time;
std::cin >> time;
if(time.find("PM") != std::string::npos)
  std::cout << "It\'s PM \n";
Run Code Online (Sandbox Code Playgroud)

  • @ 0andriy OP根本没有问过这个问题. (2认同)