My function foo(char *str)
receives str
that is a multiline string with new line characters that is null-terminated. I am trying to write a while loop that iterates through the string and operates on one line. What is a good way of achieving this?
void foo(char *str) {
while((line=getLine(str)) != NULL) {
// Process a line
}
}
Do I need to implement getLine
myself or is there an in-built function to do this for me?
You will need to implement some kind of parsing based on the new line character yourself. strtok() with a delimiter of "\\n" is a pretty good option that does something like what you're looking for but it has to be used slightly differently than your example. It would be more like:
char *tok;
char *delims = "\n";
tok = strtok(str, delims);
while (tok != NULL) {
// process the line
//advance the token
tok = strtok(NULL, delims);
}
You should note, however, that strtok() is both destructive and not threadsafe.
Sooo... a bit late, but below is a re-entrant version of @debeer's and @Christian Rau's answer - notice strtok_r
instead of strtok
. This can be called from multiple threads using different strings.
char *tok;
char *saveptr;
char *delims = "\n";
tok = strtok_r(str, delims, &saveptr);
while (tok != NULL) {
// process the line
//advance the token
tok = strtok_r(NULL, delims, &saveptr);
}
Please note that it is still destructive as it modifies the string being tokenised.
I think you might use strtok
, which tokenizes a string into packets delimited by some specific characters, in your case the newline character:
void foo(char *str)
{
char *line = strtok(str, "\n");
while(line)
{
//work with line, which contains a single line without the trailing '\n'
...
//next line
line = strtok(NULL, "\n");
}
}
But keep in mind that this alters the contents of str
(it actually replaces the '\\n'
s by '\\0'
s), so you may want to make a copy of it beforehand if you need it further.
您可以使用fgets
来完成getLine
工作: http : //linux.die.net/man/3/fgets
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.