Thread: Extracting information from stdin using scanf()

  1. #1
    Registered User
    Join Date
    Jan 2019
    Posts
    5

    Extracting information from stdin using scanf()

    Hello, I’m writing a program that reads stdin using scanf() and extracts 2 pieces of information to use later. I want to use string formatting and scanf() to do this since I’m very new to C and want to learn more about scanf().


    So far I am able to correctly extract the first part of my input, but printf outputs an incorrect value for the next part. This is the kind of input I am reading every time (I want to capture 10 characters and 1 int):

    Code:
    abcdefghij xyz 1


    I want to place abcdefghij and 1 into two separate variables. This is what I have done:

    Code:
    int main(){
    
    char myString[11];
    int myString2;
    
    scanf("%s*%d", &myString[0], &myString2);
    printf("%s  %d\n", myString, myString2);
    
    return 0;
    }
    This should output: abcdefghij 1, but instead I get: abcdefghij 0.
    There are no errors or warnings when compiling or running either. If someone could point out my mistake I would be really grateful! Thank you!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,329
    Try
    scanf("%s%*s%d", &myString[0], &myString2);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extracting Information from Files
    By Pztar in forum C Programming
    Replies: 20
    Last Post: 05-26-2011, 06:41 PM
  2. Extracting words from stdin
    By Mahesa Suprobo in forum C Programming
    Replies: 0
    Last Post: 04-30-2011, 06:00 PM
  3. Extracting information from a website?
    By gflores in forum Tech Board
    Replies: 2
    Last Post: 11-14-2005, 08:31 AM
  4. If user enters wrong information in scanf
    By Beast() in forum C Programming
    Replies: 23
    Last Post: 06-17-2004, 08:33 AM

Tags for this Thread