Thread: Input multiple floats directly to array

  1. #16
    Registered User
    Join Date
    Dec 2017
    Posts
    958
    You shouldn't have the newline character in that scanf format. It should just be:
    Code:
    scanf("%d", &len);
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  2. #17
    Registered User
    Join Date
    Nov 2019
    Posts
    135
    @john.c -
    Sorry, the tests are failed when I write the code as you have written.
    But with \n at the end - it works.

  3. #18
    Registered User
    Join Date
    Dec 2017
    Posts
    958
    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.
    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.
    Note that there is no 's' at the end of the format!!!
    What exactly is this program supposed to do?
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  4. #19
    Registered User
    Join Date
    Nov 2019
    Posts
    135
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pass array directly to new object
    By a.mlw.walker in forum C++ Programming
    Replies: 3
    Last Post: 06-14-2013, 03:03 PM
  2. Replies: 3
    Last Post: 04-09-2010, 05:07 AM
  3. how to fill multiple array locations with one input
    By kryonik in forum C++ Programming
    Replies: 5
    Last Post: 06-08-2006, 10:12 PM
  4. Replies: 3
    Last Post: 04-30-2006, 06:01 AM
  5. Input stream directly to structure elements?
    By thenrkst in forum C++ Programming
    Replies: 1
    Last Post: 04-24-2003, 11:43 AM

Tags for this Thread