如何使用 sscanf
在回车符(\r\n
或只是 \n
)上拆分字符串?
最佳答案
稍微修改 Chris 的回答,以确定第二部分何时开始:
const char *str = ... // = source string
while (str[0]) {
char buffer[100];
int n;
sscanf(str, " %99[^\r\n]%n", buffer, &n); // note space, to skip white space
str += n; // advance to next \n or \r, or to end (nul), or to 100th char
// ... process buffer
}
尽管我更喜欢使用 strtok()
或 strpbrk()
。例如:
char *str = ... // = source string--not constant, as it gets destroyed
char *out = strtok(str, "\r\n");
while (out) {
// ... process 'out'
out = strtok(0, "\r\n"); // advance to next part
}
关于c - 如何使用 sscanf 在回车符上拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335032/