Input Intricacies

Must see for specific input taking

Scanf Details

#include <stdio.h> int main()
{
    int m, n;
    scanf("(%d)-%d", &m, &n);
    printf("%d %d \n", m, n);
    // scanf accept input only if it is in same format as specified     // eg.- here if u write (8) 6 => 8 is in format
        =>m=8 but n=0 (by default) bcz not used '-'
    scanf(" (%d) - %d", &m, &n);
    printf("%d %d \n", m, n);
    // spaces doesn't matter at start or in between
    scanf("(%d)-%d ", &m, &n);
    printf("%d %d \n", m, n);
// never give space at end bcz compiler ko lgta hai ek aur value
hai aage and when u give 1 extra inputs then only it stops. => only first input get stored.
*******************************************************************
    int a;
    char c;
    scanf("%d", &a);
    //Case-1 if a=42
    //Case-2 if a=42k
    //Case-3 if a=42kl
    printf("%d\n", a);
    scanf("%c", &c);
    //Case-1 then our c is '\n'
    //Case-2 then our c is k
    //Case-3 then our c is k  (bcz char has only 1 letter)
    printf("%c \n", c);
   
//if any leftovers are there from prev. scanf then it get picked up
    return 0;
}
Cin Details
  • cin>> name1; cin>> name2;
    • I/P - Devankar Rohit
    • O/P - Devankar only
    • bcz \n after Devankar is stored as buffer and considered as input for name 2
    • USE cin.ignore() --> Clears the buffer
      • cin>> name1; cin.ignore(); cin>> name2;
  • cin>> name1; cin>> name2;
    • I/P - Devankar Raj Rohit Kumar
    • O/P - Devankar Raj
    • bcz after space everything is stored in buffer => Raj is stored as buffer and considered as input for name 2
    • USE getline(cin, name2) --> stores whole line as I/P until we encounter \n
      • getline(cin, name1) getline(cin, name2)

Comments

Popular posts from this blog

Templates (for CP)

How to Approach problem ??

DP Ideas