Help with scanf and strings

This is a discussion on Help with scanf and strings within the C Programming forums, part of the General Programming Boards category; Im currently in the process of making a programme that will read an input and then tell the user how ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    28

    Help with scanf and strings

    Im currently in the process of making a programme that will read an input and then tell the user how many vowels the string has in it.
    I have got it working 100% with gets code but i dont want to use that code, i want to use a scanf to get the user to input a string.

    Below is the code i currently have:
    Code:
    { char str[100];
    
      printf("Please type a line of text:\n");
      scanf("%s",str);
    }
    The code works perfectly with one word, but as you all most probably know scanf reads up to the first space, so when i put in something like, hello hello hello, it comes up saying 2 vowels have been found 3 times. Obviously i dont want this i want it to say 6 vowels have been found.

    Is there anyway i can make the scanf read past the spaces?

    Any help will be greatly appreciated

  2. #2
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    scanf is not capable of receiving multi-word strings. To make it receive multi-word strings you can use it like this:
    Code:
    scanf("%[^\n]s",str); //will keep receiving chars until a \n is encountered.
    But it'll be always be better to use fgets to read a string.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    thanks very much

    and yeah i know, just get use to the amount of different ways you can do things, and how certain ways make it ALOT more painful that others lol

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner Question: Problem with scanf and strings. Help!
    By lucidrave in forum C Programming
    Replies: 8
    Last Post: 08-11-2009, 11:22 PM
  2. Strings in Scanf function
    By dcwang3 in forum C Programming
    Replies: 21
    Last Post: 09-11-2008, 04:47 AM
  3. scanf for strings?
    By pobri19 in forum C Programming
    Replies: 7
    Last Post: 05-31-2008, 04:47 AM
  4. fscanf's auto-allocation for strings
    By @nthony in forum C Programming
    Replies: 12
    Last Post: 07-03-2006, 07:47 AM
  5. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 07:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21