c - 如何使用 sscanf 在回车符上拆分字符串?

标签 c

如何使用 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/

相关文章:

c - C语言的事件管理

c - 添加一个 int 到 char* 的中间(在 C 中)

c - 参数计数正确时参数太少无法运行

c - MPI编程中如何随机选择主处理器?

python - 将 Python C 库移植到 "pure"C 的问题

c - 如何在 C 中将 void 指针转换为结构?

c - 错误消息代码块 "no file or directory"

c - C 中的 realloc — 确切的行为和用途

c - 分别打印字符串中的偶数奇数字符

c - Hackerrank 挑战超时