c - 在 C 编程中使用 Char

标签 c

我是 c 编程语言的新手,我有一个与使用字符相关的大学教程作业(我不会为此作业评分),你必须计算单词,我必须编译并提交我的答案一个在线 Web 环境,我的代码将针对我不可见的测试用例运行。这是我的任务:

Write the function 'wc' which returns a string containing formatted as follows: "NUMLINES NUMWORDS NUMCHARS NUMBYTES" . Whitespace characters are blanks, tabs (\t) and new lines (\n). A character is anything that is not whitespace. The given string is null-char (\0) terminated.

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* wc(char* data) {
  char* result ;
  int numLine ;
  int numWords ;
  int numChars ;
  int i;
  int numBytes =strlen(data);
  char* empty=NULL;
  while(strstr(data,empty)>0){
    numWords=1;

    for (i = 0; i < sizeof(data); i++) {

    if(data[i]=='\n'){
     numLine++;
   }
    if(data[i]==' ' ){
     numWords++;
   }
    if(data[i]!=' '){
     numChars++;
   }
   }

   }

    sprintf(result, "%d %d %d %d", numLine, numWords, numChars, numBytes);
    return result;
}

这段代码会给我正确的输出结果,但我在这里遗漏了一些东西,至少测试告诉我这一点。

最佳答案

你有一个非常严重的错误:

  char* result;
  ...
  sprintf(result, "%d %d %d %d", numLine, numWords, numChars, numBytes);

这在C中是不允许的,需要先为字符串分配足够的内存。将 result 声明为足够大的静态数组,或者使用 malloc(如果您在类(class)中介绍过)。

例如

char buf[100];  // temporary buffer

sprintf(buf, "%d %d %d %d", numLine, numWords, numChars, numBytes);

char *result = malloc(strlen(buf) + 1);   // just enough for the string
strcpy(result, buf);                      // store the string

return result;

关于c - 在 C 编程中使用 Char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506773/

相关文章:

c - C指针数组下标,不能从0开始

c - 为什么在 SunOS 上调用 msgrcv 后得到“E2BIG”,但相同的代码在 Linux 上运行良好?

c - 递归调用中head变为0后会发生什么?

c - 编译某些 ffmpeg 应用程序时出现 gcc 奇怪的 ld 错误,找不到 libvorbisenc 包

c++ - WH_KEYBOARD 和 WH_KEYBOARD_LL 之间的区别?

c - 文件名字符串错误

c++ - 如何从 C++ 使用 FTGL C API?

c - 手动 Math.pow() 使用 float 失去精度

c++ - 在处理大于其高速缓存行的类型时,英特尔 CPU 的预期行为是什么?

android - 如何在JNI项目中实现精细的功能