【问题标题】:reading string with newlines and spaces用换行符和空格读取字符串
【发布时间】:2018-05-24 04:50:54
【问题描述】:

我正在尝试从标准输入解析一个字符串,例如 { 7 , 3,5 ,11, 8, 16, 4, 9, 2 ,8, 4, 2}(在 2 和 8 之间有一个 \n)。

我已经创建了一个函数来提取数字并修剪逗号空格和换行符(接受 char* 作为输入),但问题是当我尝试使用 scanf 获取输入时,我无法获取空格,所以我改用 fgets 但是fgets 一看到 \n 就会退出。

有没有办法可以从中获取字符串?

【问题讨论】:

  • char partA[199],partB[99]; fgets(partA,99,stream); fgets(partB,99,stream); partA[strlen(partA)-1] = 0; strcat (partA, partB); partA!

标签: c parsing scanf fgets


【解决方案1】:

您可以使用fgets 阅读整行并使用strtok 阅读数字。下面的示例还将\n 视为逗号,

char line[512];
char *buf = 0;
while(fgets(line, sizeof(line), stdin))
{
    if(!strstr(line, "{") && !buf)
        continue;

    if(!buf)
    {
        buf = strdup(line);
    }
    else
    {
        buf = realloc(buf, strlen(buf) + strlen(line) + 1);
        strcat(buf, line);
    }

    if(strstr(line, "}"))
    {
        char *token = strtok(buf, "{");
        strtok(buf, ",}\n");
        while(token)
        {
            int n = 0;
            sscanf(token, "%d", &n);
            printf("%d, ", n);
            token = strtok(NULL, ",}\n");
        }
        free(buf);
        break;
    }
}

【讨论】:

    【解决方案2】:
    int nums[1000], count = 0;
    char chr;
    while(scanf("%c%d", &chr, &nums[count]) > 0) //there was at least one match
    {
        if(chr == '}')
            break; //we have reached the end 
        if(chr != ',' && chr != '{')
            continue; //skip spaces (} is an exception)
        count++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 2010-09-12
      • 2018-03-21
      • 2013-07-28
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多