开发者

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. 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开发者_JS百科 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. To read a line from a file you normally use 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). You'd normally eliminate that by adding #include <string.h> somewhere close to the top of the file.


I don't think you want &buffer in your strtok() call. Also, you're not including string.h, which is why you're getting the warning "assignment makes pointer from integer without a cast". Without a correct prototype for strtok() available, the compiler is assuming that it returns int. The conversion of that int to char * to make the assignment to token is the assignment it's complaining about.

Edit - thanks to @dmckee for the signature of getline().


one more error is using &buffer instead of buffer.

&buffer is pointer to pointer to char, but you need pointer to char.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜