Thread: need help with scanf()

  1. #1
    Unregistered
    Guest

    need help with scanf()

    i'm having problems with the scanf() function.

    i am trying to read a string of char from standard input into my array of char

    ie.

    program extract
    -----------------------------------

    char tempStr[MAX];

    ...

    printf("Type string to read in: " );
    scanf("%s", &tempStr);

    printf("\n\nYou typed: %s\n", tempStr );

    ______________________

    now when i am prompted for a string, say



    sample output
    ______________________

    Type string to read in: this is a string

    You typed: this

    -----------------------------------


    Q) Why isn't it reading the entire line (this is a string)?

    I appreciate your feedback.

  2. #2
    aurė entuluva! mithrandir's Avatar
    Join Date
    Aug 2001
    Posts
    1,209
    Try this:

    Code:
    #include <stdio.h>
    
    #define MAX 80
    
    int main (void)
    {
    
    	char tempStr[MAX];
    
    	printf("Type string to read in: " ); 
    	gets(tempStr); 
    
    	printf("\n\nYou typed: ");
    	puts(tempStr);
    
    	return 0;
    }

  3. #3
    aurė entuluva! mithrandir's Avatar
    Join Date
    Aug 2001
    Posts
    1,209
    It's just as eay to use gets and puts in this case, although I wouldn't use them all the time for I/O. However, your program is no doubt only small, so in your case it's okay to do so.

  4. #4
    Registered User Natase's Avatar
    Join Date
    Aug 2001
    Posts
    123
    scanf("%s", &tempStr);
    Don't use a '&' in front of the variable if it's a string (only use & for int, char and float)

    scanf only reads in a single word so either use stealth's solution or read in 4 single words using scanf (if you will always have 4 words)

  5. #5
    Registered User alex's Avatar
    Join Date
    Sep 2001
    Posts
    132
    If you want scanf to read all characters up to a newline ('\n'):

    scanf("%[^\n]", tempStr);

    alex

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM