通过2的输入字符串比较 [英] Passing 2 input strings to compare

查看:157
本文介绍了通过2的输入字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了一个小程序,基本上比较2的输入字符串是否相同(如STRCMP一样)。

我愿意做这样的事情(用户在同一行中键入所需的2串)。在这种情况下,它应该返回这两个字符串是不同的

  ./ a.out的富巴

我应该这样做来读取用户输入的字符串?

  scanf函数(%s%S,STR1,STR2);

 获取(STR1);得到(STR2);

这是我迄今(它似乎停留在由于某些原因一个无限循环)

  INT mystrcmp(字符STR1 [],CHAR STR2 []){
    INT I = 0;
    而(STR1 [I] == str2的[I]){
        如果(STR1 [I] =='\\ 0'|| STR2 [I] =='\\ 0')破;
        我++;
    }
    如果(STR1 [I] =='\\ 0'和;&安培; STR2 [I] =='\\ 0')
        返回0;
    其他
        返回-1;
}INT主(INT ARGC,CHAR *的argv){
    INT CMP;
    炭STR1 [1000],STR2 [1000];
    scanf函数(%s%S,STR1,STR2);
    //得到(STR1);得到(STR2);
    CMP = mystrcmp(STR1,STR2);
    如果(CMP == 0)
        的printf(以下简称两个字符串相同\\ n);
    其他
        的printf(以下简称两个字符串是不同的\\ n);
    返回0;
}


解决方案

这个解决方案应该工作:

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;INT主(INT ARGC,CHAR *的argv []){
    如果(argc个!= 3){
        看跌期权(参数个数错误);
        返回0;
    }    如果(的strcmp(的argv [1],的argv [2]))
        看跌期权(以下简称两个字符串是不同的。);
    其他
        看跌期权(以下简称两个字符串是相同的。);
}

I'm testing a small program which basically compares whether 2 input strings are identical (as strcmp does).

I'd want to do something like (users type 2 desired strings on the same line). In this case it should return "The two strings are different"

./a.out foo bar 

should I do this to read the user's input strings?

 scanf("%s %s", str1, str2);

or

gets(str1); gets(str2);

Here is what I have so far (it seems to stuck in an infinite loop for some reasons)

int mystrcmp(char str1[], char str2[]) {
    int i = 0;
    while (str1[i] == str2[i]) {
        if (str1[i] == '\0' || str2[i] == '\0') break;
        i++;
    }
    if (str1[i] == '\0' && str2[i] == '\0')
        return 0;
    else
        return -1;
}

int main(int argc, char * * argv) {
    int cmp;
    char str1[1000], str2[1000];
    scanf("%s %s", str1, str2);
    //gets(str1); gets(str2);
    cmp = mystrcmp(str1, str2);
    if (cmp == 0)
        printf("The two strings are identical.\n");
    else
        printf("The two strings are different.\n");
    return 0;
}

解决方案

This solution should work:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if(argc != 3) {
        puts("Wrong number of arguments");
        return 0;
    }

    if(strcmp(argv[1], argv[2]))
        puts("The two strings are different.");
    else
        puts("The two strings are identical.");
}

这篇关于通过2的输入字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆