【问题标题】:Get one string with space first and get another after tabs首先获取一个带空格的字符串,然后在制表符之后获取另一个字符串
【发布时间】:2015-05-21 16:17:59
【问题描述】:

我想从 .txt 文件中获取字符串,读取每个都有姓名和电话号码的行。姓名和电话号码之间有两个 \t 字符。

例子:

name\t\t\tphone#
thomas jefferson\t\t054-892-5882
bill clinton\t\t054-518-6974

代码是这样的;

FILE *f;
errno_t err;
treeNode *tree = NULL, temp;
char input, fileName[100];

//get file name
while (1){
    printf("Enter input file name: ");
    scanf_s("%s", fileName, 100);
    //f = fopen(fileName, "r");
    if(err = fopen_s(&f, fileName, "r"))
        printf("Cannot find file!\n");
    //if (f == NULL)
    //  printf("Cannot find file!\n");
    else
        break;
}

//save info into BST
fscanf_s(f, "  NAME         Phone #\n", 20);
while (fscanf_s(f, "%[^\t]s\t\t%[^\n]s",
    temp.name, temp.phoneNo, 50, 30) != EOF)
    bstInsert(tree, temp.name, temp.phoneNo);
fclose(f);

treeNode 是一个二叉搜索树结构,bstInsert 是一个将包含第二和第三个参数的结构添加到二叉搜索树的函数。

在我用scanf_s得到文件名后,代码在fscanf_s语句处停止,在调试器上显示如下;

temp.name: invalid characters in string.

temp.phoneNo: ""

我不知道[^\t][^\n] 是如何工作的。谁能让我知道如何处理这个问题?提前致谢!

【问题讨论】:

  • 网站没有按我的意愿显示一些文本。\n 字符在每行的末尾。
  • 在编辑框中有一个“?”右上角的图标。它向您展示了如何格式化代码/....的帮助。正确大写单词也会使内容更具可读性。

标签: c regex text


【解决方案1】:

“谁能告诉我如何处理这个问题?” 我不是scanf 和家人的粉丝,所以我用不同的方法来处理这个问题。按照您使用fopen_sscanf_s 的引导,我使用了strtok 的“更安全”版本,即strtok_s

#include <stdio.h>
#include <string.h>

int main (void) {
    FILE *f;
    errno_t err;
    char *pName, *pPhone;
    char input[100], fileName[100];
    char *next_token = NULL;

    // get file name
    do{
        printf("Enter input file name: ");
        scanf_s("%s", fileName, 100);
        if(err = fopen_s(&f, fileName, "r"))
            printf("Cannot find file!\n");
    } while (err);

    // read and process each line of the file
    while(NULL != fgets(input, 100, f)) {               // has trailing newline
        // isolate name
        pName = strtok_s(input, "\t\r\n", &next_token); // strip newline too
        if (pName == NULL)                              // garbage trap
            pName = "(Error)";
        printf ("%-30s", pName);

        // isolate phone number
        pPhone = strtok_s(NULL, "\t\r\n", &next_token); // arg is NULL after initial call
        if (pPhone == NULL)
            pPhone = "(Error)";
        printf ("%s", pPhone);
        printf ("\n");
    }

    fclose(f);
    return 0;
}

使用包含示例数据的文件进行程序输出:

Enter input file name: test.txt
name                          phone#
thomas jefferson              054-892-5882
bill clinton                  054-518-6974

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多