strcmp 문의

high385의 이미지

p1.txt 내용

ab_start
ab
ab_end

p2.txt 내용

abc_start
abc
abc_end
ab_start
a
ab_end

p1.txt과 p2.txt를 통해 읽은 값을 하기 코드에서 strcmp(val1, val2)하게 되면 0이 아닌데요. 이유를 모르겠네요. debug를 해도 똑같던데요...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(int argn, char* argc[])
{
  FILE* fin = fopen("p2.txt", "r");
  FILE* fpar = fopen("p1.txt", "r");
 
  FILE* fp = fopen("out.txt", "w");
  char ori[80], par[80];
 
  fgets(par,80, fpar); // ab_start 부분에 위치
 
  char final[80];
 
  sprintf(final, "## %s", argc[4]);// 매번 바꿔줘야 할 부분이다. 
 
  while(fgets(ori,80, fin) != NULL) {
    if(strcmp(par, ori) == 0) {
      fputs (par, fp);
      char* par1 = strtok (par,"\n");
      //while(strcmp(par1, "ab_start") != 0) {  //==> 오류
      while(strncmp(par1, "ab_start", 8) != 0) { // 정상
        fgets(par,80, fpar);
        fputs (par, fp);
      }
 
      fgets(ori,80, fin);
      char *ori1 = strtok (ori,"\n");
      while(strcmp(ori1, "ab_start") != 0) {
        fgets(ori,80, fin);
      }
      fgets(ori,80, fin);
 
    }
    else {
      fputs (ori, fp);
    }
  }
 
  fclose(fin);
  fclose(fpar);
  fclose(fp);
}

==>

//while(strcmp(par1, "ab_start") != 0) { //==> 오류 ==> 왜 par1이 "ab_start"이어도 strcmp가 0이 안될까요? ==> 이유를 모르겠습니다.
while(strncmp(par1, "ab_start", 8) != 0) { // 정상 ==> 이렇게 하면 정상적으로 동작합니다.

strcmp 오류 좀 알려주세요.

세벌의 이미지

소스 전체를 보여주셔요.

김정균의 이미지

해당 코드만으로는 정확히 알 수는 없겠지만, 문제가 발생할 수 있는 요소는 3가지 정도일 것 같군요.

1. par과 ori 변수를 초기화 하지 않았을 경우, gabage data가 존재할 수 있음. malloc 후에 memset을 해 주시는 것이 좋지 않을까 생각 됩니다. (설마 malloc을 하지 않은 것은 아니겠죠? 이경우라면 segfault 가 발생하는 것이 정상인데..)
2. strcmp() == 0 의 결과를 "같지않다"라고 오인하고 있을 경우. strcmp의 결과값이 0일 경우 "같다"라는 의미를 반대로 혼동하는 경우를 종종 봅니다.

3. 이건 결과에 상관없겠지만, compiler에 따라 다른 결과를 줄 수도 있을 것 같습니다. par/ori 변수를 const char * 로 선언한 것은 char* 로 변경해 주시는 것이 warning 도 없애고 깔끔할 듯 싶습니다.

mirheekl의 이미지

라인피드 캐릭터, 뉴라인 캐릭터 등이 끼어들어서 생긴 일로 보입니다. 이런건 가끔은 디버거로도 잘 안보이죠..

비교하기 전에 그것들을 깨끗이 제거해주시면 잘 될 걸로 보입니다.

--

yukariko의 이미지

개행을 "\n"로 하셨는데, 윈도우에서 문서를 저장할 때 개행 처리는 \r\n 으로 합니다.
또한, 개행이 \n으로 저장되었다고 해도 "r" 로 오픈하게 되면 \r\n으로 바뀌게 될 수도 있습니다.
따라서 여실때 "rb"로 여시거나 strtok를 "\r\n"으로 하시는것을 추천드립니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.