Thread: How to code string of same char?

  1. #1
    zach
    Guest

    How to code string of same char?

    Code:
    char line [173];
        int x = -1;
        while(x++ <171)
        {line[x]= '-';}
        puts(line);
    Is there a better way to do this?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Probably, look at memset(). But with either method you must also insure that you properly terminate the array to create a string.

  3. #3
    zach
    Guest
    Quote Originally Posted by jimblumberg View Post
    Probably, look at memset(). But with either method you must also insure that you properly terminate the array to create a string.
    Thank you. Zach.

  4. #4
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    It should work but it looks a bit funny to initialize x with -1 and increase x as long as it is smaller than 171
    and indeed don't forget the terminating 0

    I think the code looks better if you initialize x with 0 and and increase x as long as it is smaller than 173
    For example:
    Code:
    for(x = 0; x < 173; x++)
        line[x]  = '-';
    
     line[x] = (char) 0;

  5. #5
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    oeps, the for statement should count until x < 172 since one byte is needed for the 0 character

  6. #6
    zach
    Guest
    Jim Bluberg had already responded with a better solution. Zach Kleinstein.

  7. #7
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Quote Originally Posted by zach View Post
    Jim Bluberg had already responded with a better solution. Zach Kleinstein.
    All ideas are welcome

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bus Error Appending Char to String (char array)
    By seal308 in forum C Programming
    Replies: 8
    Last Post: 02-02-2016, 12:12 PM
  2. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  3. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  4. Replies: 2
    Last Post: 09-12-2010, 09:15 AM
  5. Replies: 8
    Last Post: 12-08-2009, 02:47 AM

Tags for this Thread