You shouldn't have the newline character in that scanf format. It should just be:
Code:scanf("%d", &len);
You shouldn't have the newline character in that scanf format. It should just be:
Code:scanf("%d", &len);
The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts. - Bertrand Russell
@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?
The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts. - Bertrand Russell
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!!
Last edited by HelpMeC; 12-04-2019 at 03:47 PM.