首页 > 解决方案 > 制表符分隔的文本到 C 中的 CSV

问题描述

我需要从文件中读取制表符分隔的文本,然后将其写入 CSV 文件。我的问题是当我到达一个连续有多个选项卡的部分时。给定的 txt 文件是一个地址簿,有 37 个值。当我遇到一个制表符时, a 应该跳过它并读取下一个字符串。因此,当只有一个选项卡时,它可以正常工作。但是当有多个选项卡时,我的正则表达式会吃掉所有选项卡,直到下一个字符串然后读取它。我需要阅读两个选项卡之间的“无”。此问题导致将值存储到不适合它的字段中。例如,我有字段 firstName、lastName、fullName 和 email。如果没有 fullName 值,则会有两个选项卡,然后我的代码应该将电子邮件值存储到电子邮件。相反,它将该值存储到 fullName 字段。这是我的代码:

char* format = "%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t"
        "%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t"
        "%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\n";
    fscanf(file, format, cont.firstName, cont.lastName, cont.displayName, cont.nickname, cont.primaryEmail, cont.secondaryEmail,
        cont.screenName, cont.workPhone, cont.homePhone, cont.faxNumber, cont.pagerNumber, cont.mobileNumber,`enter code here`
        cont.homeAddress, cont.homeAddress2, cont.homeCity, cont.homeState, cont.homeZipCode, cont.homeCountry,
        cont.workAddress, cont.workAddress2, cont.workCity, cont.workState, cont.workZipCode, cont.workCountry,
        cont.jobTitle, cont.department, cont.organization, cont.webPage1, cont.webPage2, cont.birthYear, cont.birthMonth, cont.birthDay,
        cont.custom1, cont.custom2, cont.custom3, cont.custom4, cont.notes);

标签: cregextabsscanf

解决方案


推荐阅读