用于在文本文档中搜索 C 中单词的函数

如何解决用于在文本文档中搜索 C 中单词的函数

我编写了这个函数搜索文本文件(目前只显示“cube”)中的一个词,然后调用相应的函数。但是,我收到“错误:找不到函数”。留言。

谁能帮我找出我的问题?

Using a thread to poll the input-readLine:

// keystop1.sc

// In Scala- or SBT console/Quick-REPL: :load keystop1.sc
// As Script: scala -savecompiled keystop1.sc

@volatile var isRunning = true
@volatile var isPause = false

val tInput: Thread = new Thread {
  override def run: Unit = {
    var status = ""
        while (isRunning) {
            this.synchronized {
                status = scala.io.StdIn.readLine()
                status match {
                    case "s" => isRunning = false
                    case "p" => isPause = true
                    case "r" => isRunning = true;isPause = false
                    case _ => isRunning = false;isPause = false
                }
                println(s"New status is: $status")
            }
        }
    }
}

tInput.start

var count = 0
var pauseCount = 0

while (isRunning && count < 10){
  println(s"still running long lasting job! $count")
  if (count % 3 == 0) println("(Please press [each + ENTER]: s to stop,p to pause,r to run again!)")
  count += 1
  Thread sleep(2000) // simulating heavy computation
  while (isPause){
      println(s"Taking a break ... $pauseCount")
      Thread sleep(1000)
      pauseCount += 1
      if (pauseCount >= 10){
        isPause = false
        pauseCount = 0
        println(s"Taking a break ... timeout occurred!")
      }
  }
}
isRunning = false
println(s"computation stopped,please press Enter!")
tInput.join()
println(s"Ok,thank you,good bye!")

解决方法

const char cube[4] = "cube";
strstr("foobar",cube);  /* undefined behavior */

在上面,cube 不是以空字符结尾的字符串,因此当 strstr 试图读取数组的边界时会导致未定义的行为。您需要 5 个字符来存储 4 个字符的字符串。避免这个错误的最好方法是使用:

const char cube[] = "cube";

或 const char *cube = "cube";

此外,您尝试调用函数 cube 失败。

if (strstr(line,cube)!= NULL){
    void cube_f();  /* Declare a function,using a non-standard compiler extension */
    cube_f();   /* Call the function */
}

但请注意,您有名称冲突,cube 不能既是函数名又是局部变量名。我为名称添加了后缀以防止名称冲突。如果之前为您定义了 cube,您可能应该改为更改局部变量的名称。

,

所有 C 风格的字符串都必须以‘\0’结尾。 对应的代码一定要喜欢:

const char* cube= "cube";
const char* cone = "cone";
const char* sphere = "sphere";
const char* cylinder = "cylinder";

cube 是 const char 指针。 顺便说一句,“立方体”通常存储在程序的代码段或堆栈中,这取决于编译器。无论哪种方式,它都指向一个以空字符结尾的字符数组。

,

你可能想要这个:

void read() {
    const char cube_str[] = "cube"; // let the compiler determine the length
    const char cone_str[] = "cone"; // which also ensures the strings are NUL terminated
    const char sphere_str[] = "sphere";
    const char cylinder_str[] = "cylinder";

    char line[1024] ;
    FILE* fp = fopen("instructions.txt","r") ;
    if (fp == NULL)  // check for error
    {
       // display error message and abort
    }
    while (fgets(line,sizeof(line),fp ) != NULL)
    {
        if (strstr(line,cube_str)!= NULL){
            cube();    // call function instead of declaring it
                       // void cube();  is just a declaration,it 
                       // doesn't call the funtion
        }
        else if (strstr(line,cone_str)!= NULL){
            cone();
        }
        else if (strstr(line,sphere_str)!= NULL){
            sphere();
        }
        else if (strstr(line,cylinder_str)!= NULL){
            cylinder();
        }
        else {
            printf("Error: No Function Found./n");
        }
    }

    fclose(fp);
    // remove this line:  free(line);
    // you can only free pointers returned by malloc and friends
    return;
}
,

基本上,它可以归结为:在编写 C 代码时,您不能冒险了解某物的作用或工作方式。您必须真正了解您编写的每一行代码的作用。没有反复试验的学习方式,因为有些东西看似有效,但实际上是潜伏的错误,等待您的程序崩溃。

我在您的代码中发现以下问题:

  • 没有 #include 个库。我猜你是故意忽略了这一点。
  • void read() 空括号在 C 中是过时的样式(但在 C++ 中完全没问题)。编码 C 时,您应该始终执行 void read (void)
  • cube[4] = "cube" C 中的字符串以空字符结尾。你没有分配足够的空间。研究这个:How should character arrays be used as strings?
  • void cube(); 等等。我不知道你认为这是做什么的,调用一个函数?这不是你调用函数的方式。此外,由于您有一个名为 cube 的局部作用域变量,因此您会遇到命名冲突。因此该函数必须使用不同的名称。
  • free(line); 不允许在未使用 free 分配的内存上使用 malloc。只需删除此行。
  • return; 在返回 void 的函数中不是必需的。
,

其他人在您的示例中演示了一些语法错误,但没有人解决逻辑错误。您的代码(无语法错误)读取文件的每一行,并在该行包含某些子字符串时做出反应。

这意味着,如果一行文本包含单词“iconography”(原文如此),这将触发您的“cone”处理逻辑。此外,如果一行同时包含单词“cube”和“cone”,那么只有你的多维数据集逻辑会触发。

要克服这个问题,您需要将行拆分为单独的单词。您可以通过扫描空格并一次处理一个单词来完成此操作。

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

// warning,this code is untested,but should send you in the right direction

char *find_word(char *input)
{
    while (isspace(input) && *input != '\0')
    {
        input += sizeof(char);
    }
    return input;
}

char *find_whitespace(char *input)
{
    while (!isspace(input) && *input != '\0')
    {
        input += sizeof(char);
    }
    return input;
}

void process_word(char *word,size_t len)
{
    if (strncmp(start,"cube",len) == 0)
    {
        // do something
    }
    else if (strncmp(start,"cone","sphere","cylinder",len) == 0)
    {
        // do something
    }
}

int main(int argc,char *argv[])
{
    FILE *fp = fopen(argv[1]);
    char line[1024];

    while (fgets(line,fp) != NULL)
    {
        char *cursor = line;
        while (*cursor != '\0')
        {
            char *start = find_word(line);
            char *end = find_whitespace(start);
            process_word(start,end - start);
            cursor = end;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?