문자열을 올바르게 비교하려면 어떻게합니까?
사용자가 단어 나 문자를 입력하고 저장 한 다음 사용자가 다시 입력 할 때까지 인쇄하여 프로그램을 종료 할 수있는 프로그램을 얻으려고합니다. 내 코드는 다음과 같습니다
#include <stdio.h>
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
gets(input);
printf("I will now repeat this until you type it back to me.\n");
while (check != input)
{
printf("%s\n", input);
gets(check);
}
printf("Good bye!");
return 0;
}
문제는 사용자의 입력 (확인)이 원본 (입력)과 일치하더라도 입력 문자열을 계속 인쇄한다는 것입니다. 두 가지를 잘못 비교하고 있습니까?
당신은 (유용)를 사용하여 문자열을 비교할 수 없습니다 !=
또는 ==
사용할 필요가 strcmp
:
while (strcmp(check,input) != 0)
때문에 그 이유는 !=
하고 ==
만 문자열의 기본 주소를 비교합니다. 문자열 자체의 내용이 아닙니다.
몇 가지 확인 : gets
안전 fgets(input, sizeof(input), stdin)
하지 않으며 버퍼 오버플로가 발생하지 않도록 대체해야합니다 .
다음으로 문자열을 비교하려면을 사용해야합니다 strcmp
. 여기서 반환 값 0은 두 문자열이 일치 함을 나타냅니다. 항등 연산자 (즉, !=
)를 사용하면 두 문자열의 주소가 char
내부 의 개별 문자열과 비교되는 것과 비교 됩니다.
또한이 예제에서는 문제를 일으키지 않지만 fgets
개행 문자를 '\n'
버퍼에도 저장합니다 . gets()
하지 않습니다. 사용자 입력을 fgets()
문자열 리터럴과 비교하면 "abc"
절대 일치하지 않을 것입니다 (버퍼가 너무 작아서 '\n'
맞지 않을 경우).
편집 : 그리고 다시 한 번 슈퍼 빠른 미스틱에 의해 구타.
사용하십시오 strcmp
.
이것은 string.h
도서관에 있으며 매우 인기가 있습니다. strcmp
문자열이 같으면 0을 반환합니다. 무엇이 반환 되는지에 대한 더 자세한 설명은 이것을 참조하십시오strcmp
기본적으로 다음을 수행해야합니다.
while (strcmp(check,input) != 0)
또는
while (!strcmp(check,input))
또는
while (strcmp(check,input))
확인할 수 있습니다 이 ,에 대한 자습서를 strcmp
.
이처럼 직접 배열을 비교할 수 없습니다
array1==array2
당신은 그것들을 문자별로 비교해야합니다; 이를 위해 함수를 사용하고 부울 (True : 1, False : 0) 값을 반환 할 수 있습니다. 그런 다음 while 루프의 테스트 조건에서 사용할 수 있습니다.
이 시도:
#include <stdio.h>
int checker(char input[],char check[]);
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
scanf("%s",input);
printf("I will now repeat this until you type it back to me.\n");
scanf("%s",check);
while (!checker(input,check))
{
printf("%s\n", input);
scanf("%s",check);
}
printf("Good bye!");
return 0;
}
int checker(char input[],char check[])
{
int i,result=1;
for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
if(input[i] != check[i]) {
result=0;
break;
}
}
return result;
}
포인터 의 개념에 오신 것을 환영합니다 . 여러 세대의 초보 프로그래머가이 개념을 이해하기 어려웠지만 유능한 프로그래머로 성장하려면 결국이 개념을 숙달해야합니다. 또한 이미 올바른 질문을하고 있습니다. 잘 됐네요
Is it clear to you what an address is? See this diagram:
---------- ----------
| 0x4000 | | 0x4004 |
| 1 | | 7 |
---------- ----------
In the diagram, the integer 1 is stored in memory at address 0x4000. Why at an address? Because memory is large and can store many integers, just as a city is large and can house many families. Each integer is stored at a memory location, as each family resides in a house. Each memory location is identified by an address, as each house is identified by an address.
The two boxes in the diagram represent two distinct memory locations. You can think of them as if they were houses. The integer 1 resides in the memory location at address 0x4000 (think, "4000 Elm St."). The integer 7 resides in the memory location at address 0x4004 (think, "4004 Elm St.").
You thought that your program was comparing the 1 to the 7, but it wasn't. It was comparing the 0x4000 to the 0x4004. So what happens when you have this situation?
---------- ----------
| 0x4000 | | 0x4004 |
| 1 | | 1 |
---------- ----------
The two integers are the same but the addresses differ. Your program compares the addresses.
Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>
Try this code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s[]="STACKOVERFLOW";
char s1[200];
printf("Enter the string to be checked\n");//enter the input string
scanf("%s",s1);
if(strcmp(s,s1)==0)//compare both the strings
{
printf("Both the Strings match\n");
}
else
{
printf("Entered String does not match\n");
}
system("pause");
}
Unfortunately you can't use strcmp
from <cstring>
because it is a C++ header and you specifically said it is for a C application. I had the same problem, so I had to write my own function that implements strcmp
:
int strcmp(char input[], char check[])
{
for (int i = 0;; i++)
{
if (input[i] == '\0' && check[i] == '\0')
{
break;
}
else if (input[i] == '\0' && check[i] != '\0')
{
return 1;
}
else if (input[i] != '\0' && check[i] == '\0')
{
return -1;
}
else if (input[i] > check[i])
{
return 1;
}
else if (input[i] < check[i])
{
return -1;
}
else
{
// characters are the same - continue and check next
}
}
return 0;
}
I hope this serves you well.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50],s2[50];
printf("Enter the character of strings: ");
gets(s1);
printf("\nEnter different character of string to repeat: \n");
while(strcmp(s1,s2))
{
printf("%s\n",s1);
gets(s2);
}
return 0;
}
This is very simple solution in which you will get your output as you want.
How do I properly compare strings?
char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow
// insufficient
while (check != input)
// good
while (strcmp(check, input) != 0)
// or
while (strcmp(check, input))
Let us dig deeper to see why check != input
is not sufficient.
In C, string is a standard library specification.
A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1
input
above is not a string. input
is array 40 of char.
The contents of input
can become a string.
In most cases, when an array is used in an expression, it is converted to the address of its 1st element.
The below converts check
and input
to their respective addresses of the first element, then those addresses are compared.
check != input // Compare addresses, not the contents of what addresses reference
To compare strings, we need to use those addresses and then look at the data they point to.
strcmp()
does the job. §7.23.4.2
int strcmp(const char *s1, const char *s2);
The
strcmp
function compares the string pointed to bys1
to the string pointed to bys2
.The
strcmp
function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to bys1
is greater than, equal to, or less than the string pointed to bys2
.
Not only can code find if the strings are of the same data, but which one is greater/less when they differ.
The below is true when the string differ.
strcmp(check, input) != 0
For insight, see Creating my own strcmp()
function
참고URL : https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings
'development' 카테고리의 다른 글
C # 코드에서 .NET 4.0 튜플을 사용하는 것이 좋지 않은 디자인 결정입니까? (0) | 2020.05.28 |
---|---|
GitHub 관련 문제에 대한 의견을 어떻게 추적합니까? (0) | 2020.05.28 |
Angular 프로젝트에서 부트 스트랩을 사용하는 방법은 무엇입니까? (0) | 2020.05.28 |
다양한 캐시 및 메인 메모리에 액세스하는 데 드는 대략적인 비용은? (0) | 2020.05.28 |
XMLHttpRequest의 응답을 얻는 방법? (0) | 2020.05.28 |