【问题标题】:Last word is Failing ...?最后一句话是失败......?
【发布时间】:2014-10-15 12:07:02
【问题描述】:

我对最后一个词有疑问,它似乎错过了最后一步。

输入:

JXJIAA

输出:

lowercase: 0.00 uppercase: 77.78

应该是什么时候

lowercase: 0.00 uppercase: 100.00?

如果文本文件中有另一行,则程序可以工作,但我希望它在没有额外行的情况下工作,我想我与此有关:“while (line[x] != 10); "但不知道该怎么办? 有什么方法可以改进此代码。代码如下:

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

FILE *fr; 

int main (int argc, const char * argv[]){
    char line[1024];
    double uppercase = 0, lowercase = 0;
    int x = 0;
    fr = fopen ("PercenUpLow.txt", "rt");
    while(fgets(line, 1024, fr) != NULL){
        do{
            if ((line[x] >= 'A') && (line[x] <= 'Z')){
                uppercase += 1;
            }else if ((line[x] >= 'a') && (line[x] <= 'z')){
                lowercase += 1;    
            }
                x+=1;
            }while (line[x] != 10);
            printf("lowercase: %0.2f ", (lowercase / x) * 100);
            printf("uppercase: %0.2f \n", (uppercase / x) * 100);
            lowercase = 0;
            uppercase = 0;
            x = 0;
        }    
    return EXIT_SUCCESS;
}

示例:

输入:

HeLo

输出:

Uppercase: 50.00 Lowercase: 50.00

【问题讨论】:

  • 您到底在哪里遇到了分段错误,您是否尝试过使用调试器单步执行您的代码?
  • 测试frfopen 之后是否为NULL,如果是则显示错误消息并且不要进一步。
  • "任何建议都将不胜感激" 遗憾的是,这是一种提出无法以 SO 期望答案设计的方式回答的问题的方式。
  • @MattSolo 然后在您的机器上安装一个编译器+调试器并尝试那里的代码?在线编译器不适合编程,特别是如果它们甚至不给你基本的调试支持,就像这个似乎做的那样。然而 Michael Walz 的建议似乎是最可能的原因(特别是因为我猜该网站无权访问您尝试打开的文件)
  • @MichaelWalz 我不知道,我想我可能会创建一个与我的程序同名的文本文档,名为 PercenUpLow.c。显然我错了,觉得自己很愚蠢。

标签: c segmentation-fault


【解决方案1】:

试试这个:

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

FILE *fr; 

int main (int argc, const char * argv[]){
  char line[1024];
  double uppercase = 0, lowercase = 0;
  int x = 0;
  fr = fopen ("PercenUpLow.txt", "rt");
  if (fr == NULL) {
    printf ("Can't open file") ;
    return EXIT_FAILURE ;
  }
  while(fgets(line, 1024, fr) != NULL) {
    do {
      if ((line[x] >= 'A') && (line[x] <= 'Z')){
        uppercase += 1;
      }else if ((line[x] >= 'a') && (line[x] <= 'z')){
        lowercase += 1;    
      }
      x+=1;
    } while (line[x] != '\n' && line[x] != 0);

    printf("lowercase: %0.2f ", (lowercase / x) * 100);
    printf("uppercase: %0.2f \n", (uppercase / x) * 100);
    lowercase = 0;
    uppercase = 0;
    x = 0;
  }    
  return EXIT_SUCCESS;
}

我改变了这一行:

     } while (line[x] != '\n' && line[x] != 0);

如果文件没有被\n 终止,那么读取的最后一行也不会被\n 终止(似乎很明显)并且您正在阅读的内容超出了行尾,从而导致未定义的行为。

我也测试一下文件是否可以正确打开。

您绝对应该学习如何使用调试器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多