Thread: Trouble with scanning 2 strings in same scanf call

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    49

    Trouble with scanning 2 strings in same scanf call

    Somehow only str2 is succesfully scanned and str1 is not printed
    Code:
       printf("\n\n  Please enter two times in this way xx.xx xx.xx now ");
       scanf("%s%s", str1, str2);
       printf("\n\n  %s - %s:\n", str1, str2));
    result : - str2:

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    This is incorrect. Assuming you type two separate strings (ie separated by spaces with no other punctuation), they are both picked up by scanf.

    Note: I have assumed you have declared str1 and str2 as char arrays, or char pointers pointing to separate pieces of memory. If you have (for instance) pointed them at the same piece of memory, then that can also cause errors.

  3. #3
    Registered User
    Join Date
    Nov 2013
    Posts
    49
    So should i have two separate scanf calls or is it possible with 1?, i tried writing scanf("%5s%5s", str1, str2); to no avail

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    What you have works; or if it doesn't work, the error is elsewhere. In other words this code:
    Code:
    #include<stdio.h>
    
    int main(void) {
    
        char str1[80], str2[80];
        printf("\n\n Please enter two times in this way xx.xx xx.xx now ");
        scanf("%s%s", str1, str2);
        printf("\n\n %s - %s:\n", str1, str2);
        return 0;
    }
    correctly gives you two different strings:
    Code:
    C:\Users\tabstop\Desktop>temp
    
     Please enter two times in this way xx.xx xx.xx now 22.25 23.15
    
     22.25 - 23.15:
    
    C:\Users\tabstop\Desktop>

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-29-2011, 01:02 PM
  2. scanning strings and integers from a file
    By GaelanM in forum C Programming
    Replies: 15
    Last Post: 03-31-2011, 09:38 PM
  3. trouble scanning in... and link listing
    By panfilero in forum C Programming
    Replies: 14
    Last Post: 11-21-2005, 12:58 PM
  4. Help with scanning in strings
    By cdonlan in forum C Programming
    Replies: 3
    Last Post: 11-08-2004, 05:23 PM
  5. Scanning characters & strings
    By rain_e in forum C Programming
    Replies: 2
    Last Post: 03-04-2002, 01:43 AM