我是 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/