【问题标题】:Issue with scanf(...) and fgets(...)scanf(...) 和 fgets(...) 的问题
【发布时间】:2014-11-13 16:53:43
【问题描述】:

我正在做alternating characters problem

问题:

Shashank 喜欢连续字符不同的字符串。 例如,他喜欢ABAA,而他不喜欢ABAA。给定一个 仅包含字符 A 和 B 的字符串,他想将其更改为 他喜欢的一根弦。为此,他可以删除字符 在字符串中。

您的任务是找出所需删除的最少数量。

输入格式第一行包含一个整数T,即 测试用例。接下来的 T 行每行包含一个字符串。

输出格式打印每个测试所需的最少步骤数 案例。

约束

1≤T≤10 1≤字符串长度≤105

我的代码:

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

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int t,i,j;
    scanf("%d", &t);

    char line[100000];

    for(i=0; i < t; i++){
        //get string from user
        fgets(line, sizeof(line), stdin);
        //loop line and greedily solve this
        int deletions = 0;
        if(strlen > 0){
            char currentChar = line[0];
            for(j=1; j < strlen(line); j++){
                if(currentChar == line[j]){
                    deletions++;
                }else{
                    currentChar = line[j];
                }
            }
        }
        printf("%d\n", deletions);
        //empty string
        memset(line,0,strlen(line));
    }

    return 0;
}

输入:

5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB

我的输出:

0
3
4
0
0

预期输出:

3
4
0
0
4

我不是 C 专家,所以如果这是一个明显的问题,我很抱歉。似乎我的fgets 在不应该的时候捕获了一个空行。我的猜测是它与scanf 有关。但是,我不知道为什么,也不知道如何解决?

【问题讨论】:

  • if(strlen &gt; 0) --> if(strlen(line) &gt; 0)
  • @weathervane 好收获!

标签: c


【解决方案1】:

在您忽略的“5”之后的文件中有一个换行符,应该是:

scanf("%d\n", &t);

当然假设你有一个 unix 文件(例如,只有 \n 作为新行)

【讨论】:

  • 可以在 Windows 上工作,并且标准输入在文本模式下打开。
  • 的东西很明显哈。我会尽快标记为正确。
  • 并且可以在 Windows 上工作,因为 \n 匹配每个空白字符("%d ""%d\n" 是等效的格式字符串)。
【解决方案2】:

只有当您没有吞下输入数据第一行中的“\n”时,才会出现此问题。您可以使用简单的getchar() 来捕捉该字符:

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

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int t,i,j;
    scanf("%d", &t);

    char line[100000];

    getchar();   /// HERE!!!!!
    for(i=0; i < t; i++){
        //get string from user
        fgets(line, sizeof(line), stdin);
        //loop line and greedily solve this
        int deletions = 0;
        if(strlen > 0){
            char currentChar = line[0];
            for(j=1; j < strlen(line); j++){
                if(currentChar == line[j]){
                    deletions++;
                }else{
                    currentChar = line[j];
                }
            }
        }
        printf("%d\n", deletions);
        //empty string
        memset(line,0,strlen(line));
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    相关资源
    最近更新 更多