sscanf 에서 문자열 저장 길이 제한 방법

zzup의 이미지

char p1[5];
char p2[5];

sscanf(source, "%s %s", p1, p2);

위와 같은 경우 p1으로 저장될 자료는 4바이트를 넘어서는 안되겠지만,
만약 source가 "123456 9876"라고 하면 p1이 overflow될것 같은데 이를 해소하는 방법(sprintf를 대신하는 snprintf 같은 n 계열 함수라든가...)이 없을까요?

doldori의 이미지

필드폭을 같이 쓰세요. 널 문자가 들어갈 1바이트를 고려해야 합니다.

char p1[5]; 
char p2[5]; 

sscanf(source, "%4s %4s", p1, p2); 
zzup의 이미지

doldori wrote:
필드폭을 같이 쓰세요. 널 문자가 들어갈 1바이트를 고려해야 합니다.
char p1[5]; 
char p2[5]; 

sscanf(source, "%4s %4s", p1, p2); 

자료가 고정폭이 아니기 때문에 다음 처럼 되더군요. ㅡ,ㅡ;;;

#include <stdio.h>

int main (int argc, char ** argv)
{
    char p1[5];
    char p2[5];
    char source[] = "123456 9876";

    sscanf(source, "%4s %4s", p1, p2);
    printf("p1 : %s\n", p1);
    printf("p2 : %s\n", p2);
    return 0;
}

** 결과
p1 : 1234
p2 : 56 <-- "9876"이 출력되야 하는데...

doldori의 이미지

그렇군요. source 문자열을 만들 때부터 토큰별로 자르는 과정이 필요하겠네요.

char p[5]; 
char source[256]; // sufficient space to hold a tokenized string
while (fscanf(stdin, "%255s", source) == 1)
{
	sscanf(source, "%4s", p);
	printf("%s\n", p);
}
alwaysN00b의 이미지

나중에 보니 제가 주제를 잘못 파악했군요.. 쪽팔려서 지우고 갑니다.
:oops:

언제나 시작

musik의 이미지

#include <stdio.h>

int main (int argc, char ** argv)
{
    char p1[5];
    char p2[5];
    char source[] = "123456789 98765";

    sscanf(source, "%4s%* %4s", p1, p2);
    printf("p1 : %s\n", p1);
    printf("p2 : %s\n", p2);
    return 0;
}
freestyle의 이미지

#include <stdio.h>
 
 
int main(void)
{
    char *src = "123456 987654";
 
    char p1[5];
    char p2[5];
 
 
    sscanf(src, "%4s%*[^ ]%4s", p1, p2);
 
    printf("[%s] [%s]\n", p1, p2);
 
 
    return 0;
}

sscanf에서...
1. %4s에서 4는 %s로 읽을 character의 max length를 지정함
2. %s로 읽은 문자 배열을 자동으로 null termination시킴
3. *는 해당 포맷스트링으로 읽는 것을 저장하지 않고 버림(discard)함
4. %[^ ]는 scanset(표준임)으로 ' '(space) 문자가 나오기 전까지 문자열을 지칭함
(3에 의해 4번으로 읽은 문자열은 discard. 곧, 공백 전까지의 나머지 문자열을 버림)
5. %s로 읽는 것은 white space를 skip함. 따라서 공백 뒤의 문자부터 새로 읽음

보통은 파일에서 한 줄씩 읽어 파싱할 때, fgets와 sscanf면 충분하더군요.
proc 파싱할 때나, 자료구조를 파일에 읽고 쓸 때 유용하게 사용했습니다.

자세한 내용은 hyperhidrosis님이 예전에 올려주신 링크를 참조하심이..
-----------------------------------
Go to the U-City

----------------------------------------------------------------------------------------
Don't Feed the Trolls!
----------------------------------------------------------------------------------------

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.