Thread: How to store string enterd by user in c

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    99

    How to store string enterd by user in c

    How to store string entered by user like string = jen, sen,dnny, rema,clrb

    Code:
    #include<stdio.h>
    int main(void)
    {
     int i;
        char string [5];
     printf("Enter String");
     scanf("%s",&string);
     
     for(i=0; i<5; i++)
      
      {
       printf("Strings %s",string[i]);
      }
      return 0;
    }
    What's the wrong in program ?

  2. #2

  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    99
    I have looked link you pointed but still I can't figure out what's wrong in my program. Can you help me with my program

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    Quote Originally Posted by vead View Post
    I have looked link you pointed but still I can't figure out what's wrong in my program. Can you help me with my program
    If the sort of string that you want to store really looks like this: "jen, sen,dnny, rema,clrb" then your approach is doomed to fail and you are better off following the advice of the article.

    The problems are numerous, and all of them feel deliberate errors on your part.

    1) string is declared as a char array of length 5. This means that, if it is used as a string, it will sufficiently store a single, 4-character long, '\0'-terminated word and that is it. Your input is dangerous because it is much longer.
    2) scanf() is being called incorrectly with a &string argument, even though I'm sure you've been corrected on this in the past.
    3) you are printing your one string like it was actually an array of strings

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Best way to store an input string
    By workisnotfun in forum C Programming
    Replies: 2
    Last Post: 09-16-2013, 10:57 PM
  2. Replies: 10
    Last Post: 07-10-2012, 04:28 AM
  3. How to store a user input string into dynamic array?
    By sethwb in forum C++ Programming
    Replies: 4
    Last Post: 04-25-2011, 04:48 AM
  4. Replies: 3
    Last Post: 11-01-2010, 08:22 PM
  5. Replies: 2
    Last Post: 10-08-2005, 04:09 PM

Tags for this Thread