[C/C++] txt파일에 있는 내용을 받아올 때 특정 문자를 제외하고 받아오구 싶어요

ysh667의 이미지

안녕하세요. 초보자입니다ㅠㅠ
제목 그대루 txt 파일에 있는 내용을 받아와야 하는데
아무리 찾아봐도 잘 모르겠어서.. 여기 남겨봐요 ㅠㅠ

파일은

1: 10, 100, 50

이런식으루 되어있고
':', ',', ' ' 를 제외하고
1, 10, 100, 50을 각각 받아와야하는데 어떤 방법이 있을까요..?
알려주시면 감사하겠습니다.
아, 학교 과제는 아니에요 !!

익명 사용자의 이미지

콜론 뒤에 항상 숫자가 3개 뿐이라면 간단히 해결됩니다. scanf는 그럭저럭 기능이 많거든요.

#include <stdio.h>
 
int main(void){
        int a, b, c, d;
        while(scanf("%d : %d , %d , %d", &a, &b, &c, &d) == 4){
                printf("%d : %d , %d , %d\n", a, b, c, d);
        }
        return 0;
}

더 유연한 기능을 바란다면, 예컨대 콜론 뒤에 숫자가 전혀 없거나, 3개보다 적거나, 3개보다 많거나 하는 경우까지 전부 커버해야 한다면 문제가 복잡해집니다. 기초적인 수준의 파싱(Parsing)이라고 할 만한데 그렇다고 parser generator를 쓸 생각까지는 안 들게 만드는군요.

아예 라인 단위로 입력받은 뒤 구분자를 하나하나 검색해서 찾거나 정규표현식을 쓰거나 하는 방법도 있지만, 뭐 앞서 scanf를 써서 해결해보기도 했으니 이번엔 cin을 이용해 해결해 봅시다. 사실 C언어로 가변 길이 데이터를 다루는 건 너무 귀찮아요.

#include <iostream>
#include <cstdio>
#include <limits>
#include <vector>
using namespace std;
 
int main(void){
        int tmp;
        while(cin >> tmp){
                int before_colon = tmp;
                vector<int> int_list;
 
                cin.ignore(numeric_limits<streamsize>::max(), ':');
 
                while(true){
                        tmp = cin.peek();
 
                        if(tmp == EOF)
                                break;
                        else if(isspace(tmp) || tmp == ','){
                                cin.ignore();
                                if(tmp == '\n')
                                        break;
                                else
                                        continue;
                        }
 
                        cin >> tmp;
                        int_list.push_back(tmp);
                }
 
                cout << before_colon << " : ";
                for(vector<int>::iterator I=int_list.begin();I!=int_list.end();I++){
                        cout << *I << " , ";
                }
                cout << "\n";
        }
        return 0;
}

좀 대충 짜서 예외 처리라던가 그런 부분이 많이 부족하니 참고만 하시고 직접 작성해 보시기 바랍니다.

덧. code에서 >>와 <<이 깨져 나오고 있는데 문맥상 알아볼 수 있으실 거라고 믿습니다. 왜 이렇게 깨져 나오는지는 잘 모르겠군요.

ysh667의 이미지

정말감사해요~!!! ^^

bushi의 이미지

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
        char buf[1024], *p;
        while ((p = fgets(buf, sizeof(buf), stdin))) {
                char *s = p, *e = p;
                while (*e != '\0') {
                        long val = strtol(s, &e, 10);
                        if (e != s)
                                printf("%ld\n", val);
                        s = e + 1;
                }
        }
        return 0;
}

$ echo "1: 10, 100, 50, foo % 1000bar" | ./test
1
10
100
50
1000

댓글 달기

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