You shouldn't have the newline character in that scanf format. It should just be:
Code:scanf("%d", &len);
Printable View
You shouldn't have the newline character in that scanf format. It should just be:
Code:scanf("%d", &len);
@john.c -
Sorry, the tests are failed when I write the code as you have written.
But with \n at the end - it works.
Oh, you're right. Except that the way we would usually handle it is by adding an extra space (just a space, not a newline) in front of the format of your other scanf.
Note that there is no 's' at the end of the format!!!Code:int len = 0;
scanf("%d", &len);
if (len == 0)
return 0;
char* str = malloc(len + 1); // sizeof(char) is always (literally defined to be) 1, so it's not needed here
scanf(" %[^\n]", str); // extra space before format here causes whitespace (including newlines) to be skipped first.
What exactly is this program supposed to do?
John - This is exactly the exercise of this topic.
Actually, I don't have any problem with the second scanf - only with the first one, when it looks like the first scanf you wrote - some tests are failed.
But, when I'm adding \n after %d - everything is just fine.
Zeus - The reason to these both conditions is that this length indicates only the maximum possible chars to iterate over - so the null-terminator can be occurred at any iteration...
EDIT:
John - got it.
Thank you guys!!