[英]How to use getline and strtok together in C?
this is my first time asking a question here so I hope I am doing it correctly! 这是我第一次在这里提问,希望我能正确做! For a while now I have been trying to get getline and strtok to work together in order to read text from a file and break it into words. 一段时间以来,我一直在尝试使getline和strtok一起工作,以便从文件中读取文本并将其分解为单词。 Essentially the text file input is an essay and I want to manipulate each word individually later on. 从本质上讲,文本文件输入是一篇论文,以后我想分别处理每个单词。 The problem I am getting is a constant "assignment makes pointer from integer without a cast"; 我得到的问题是一个常量“赋值使指针从整数开始而没有强制转换”; I have tried everything I can think of. 我已经尝试了所有我能想到的。 This is my code as of right now: 这是我目前的代码:
int nbytes = 100;
char *buffer;
char *token;
buffer = (char *) malloc(nbytes + 1);
getline(&buffer,&nbytes,file);
token = strtok(&buffer, " ");
I feel like it's problem something really simple that I am overlooking. 我觉得我忽略了一个非常简单的问题。 That you for reading and your help! 那对您的阅读和您的帮助!
Standard C (on its own) doesn't define anything named getline
. 标准C(本身)没有定义任何名为getline
东西。 To read a line from a file you normally use fgets
. 要从文件中读取一行,通常使用fgets
。
The error you describe sounds like you don't have a prototype for strtok
in scope, so the compiler is treating it as if it returned the default type (int). 您描述的错误听起来像在范围内没有strtok
的原型,因此编译器将其视为返回了默认类型(int)。 You'd normally eliminate that by adding #include <string.h>
somewhere close to the top of the file. 通常,您可以通过在文件顶部附近添加#include <string.h>
来消除这种情况。
I don't think you want &buffer
in your strtok()
call. 我认为您在strtok()
调用中不需要&buffer
。 Also, you're not including string.h
, which is why you're getting the warning "assignment makes pointer from integer without a cast". 另外,您不包括string.h
,这就是为什么您收到警告“赋值使指针从整数开始而没有强制转换”的原因。 Without a correct prototype for strtok()
available, the compiler is assuming that it returns int
. 如果没有可用的strtok()
正确原型,编译器将假定它返回int
。 The conversion of that int
to char *
to make the assignment to token
is the assignment it's complaining about. 将该int
转换为char *
以将其分配给token
是它所抱怨的分配。
Edit - thanks to @dmckee for the signature of getline()
. 编辑-感谢@dmckee为getline()
签名。
one more error is using &buffer instead of buffer. 还有一个错误是使用&buffer而不是buffer。
&buffer is pointer to pointer to char, but you need pointer to char. &buffer是指向char的指针,但是您需要指向char的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.