用C比较字符串 [英] Comparing strings in C

查看:150
本文介绍了用C比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,通过行从.txt文件中使用fgets和缓冲区声明为读学生的姓名和成绩行:

I have a program that reads student names and grades line by line from a .txt file using fgets and a buffer declared as:

char buffer[1024];

现在该文件应该以一行字符串END结束所有的本身。

Now the file should end with the string "end" on a line all by itself.

我如何知道一个while循环时终止缓冲==结束

How do I tell a while loop to terminate when buffer == "end"?

我试着用 STRCMP ,但它出现segfaults出于某种原因。

I tried using strcmp but it segfaults for some reason.

推荐答案

要简单地回答你的问题,实际上的strcmp 的您正在寻找的功能:

To simply answer your question, strcmp actually is the function you're looking for:

#include <string.h>

if(!strcmp(line, "end\n") || !strcmp(line, "end\r\n"))
    break;

或类似的应该做的伎俩。注意中的strcmp的前面,STRCMP返回0(即假)如果字符串匹配。不过,我想你已经知道,因为你已经在你的问题中提到的strcmp。

or similar should do the trick. Note the ! in front of strcmp as strcmp returns 0 (i.e. false) if the strings match. But I guess you already know that since you've already mentioned strcmp in your question.

在该段错误的问题:你肯定没有指针传递到strcmp为NULL?大多数C标准库不做任何错误检查这里,并试图读取的内存时会遇到段错误*(0)

On the segfault issue: Are you sure none of the pointers you pass to strcmp are NULL? Most C standard libraries don't do any error checking here and will run into segfaults when trying to read the memory at *(0).

这跃入我的脑海另一个可能的问题是,使用STRCMP会,如果你已经分裂您的缓冲区为单一字符串数组当然只是工作。 strtok_r 可能是最适合这项任务(Altough的相当棘手使用)。

Another possible issue that pops into my mind is that using strcmp will of course only work if you've already split your buffer into an array of single strings. strtok_r is probably most suited for this task (Altough quite tricky to use).

这篇关于用C比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆