C printf中%s之后的所有字符都打印在行首

C printf中%s之后的所有字符都打印在行首,c,string,printf,C,String,Printf,我正在从一个文件中读取,知道该行将是100个字符或更少 char *nodeDetails = malloc(sizeof(char[100])); // Object name or question char temp[10]; // Question or Object text used to identify line sscanf(text, "%[Question|Object]: %[^\n]", temp, nodeDetails); 我正确地阅读了这一行,然后在稍后的程序中

我正在从一个文件中读取,知道该行将是100个字符或更少

char *nodeDetails = malloc(sizeof(char[100])); // Object name or question
char temp[10]; // Question or Object text used to identify line
sscanf(text, "%[Question|Object]: %[^\n]", temp, nodeDetails);
我正确地阅读了这一行,然后在稍后的程序中尝试打印它

printf("Is it %s?\n", currentNode->objectName);
输出变为:

?t is an alligator
鉴于它应该是:

Is it an alligator?
如果我没有从文件中读取该行,而只是使用动态分配的字符串手动设置objectName。它很好用。 例如

我厌倦了将内存重新定位到正确的大小

sizeof(char[strlen(currentNode->objectName)]);
它仍然做同样的事情。所以我迷路了


知道如何修复它吗?

代码有多个问题

// sscanf(text, "%[Question|Object]: %[^\n]", temp, nodeDetails);
// Check result, drop |, add widths
if (2 != sscanf(text, "%9[QuestionObject]: %99[^\n]", temp, nodeDetails))
  HandleUnexpectedInput();

// This prints wrong because `currentNode->objectName` still has an `\n` in the end of it.
printf("Is it %s?\n", currentNode->objectName);

// As mentioned by x4rf41, add 1.
sizeof(char[strlen(currentNode->objectName) + 1]);

调试器确实有助于解决此类问题,您应该在
sscanf
之后和
printf
之前检查
temp
nodeDetails
。还有这个
sizeof(char[strlen(currentNode->objectName)]
不正确,因为NUL终止需要
+1个字符
(并确保其实际为0)。您是@x4rf41的救生员!谢谢我将其重新定位为
length+1
,然后设置
objectName[newLength-1]='\0'
,解决了这个问题@x4rf41您想将您的评论作为答案发布,以便我可以接受吗?
// sscanf(text, "%[Question|Object]: %[^\n]", temp, nodeDetails);
// Check result, drop |, add widths
if (2 != sscanf(text, "%9[QuestionObject]: %99[^\n]", temp, nodeDetails))
  HandleUnexpectedInput();

// This prints wrong because `currentNode->objectName` still has an `\n` in the end of it.
printf("Is it %s?\n", currentNode->objectName);

// As mentioned by x4rf41, add 1.
sizeof(char[strlen(currentNode->objectName) + 1]);