? about breaking up a string into indivual chars

This is a discussion on ? about breaking up a string into indivual chars within the C Programming forums, part of the General Programming Boards category; Hi, I'm trying to break a line up into individual chars. This is what I tried but it doesn't work!: ...

  1. #1
    Stringz
    Guest

    Question ? about breaking up a string into indivual chars

    Hi, I'm trying to break a line up into individual chars. This is what I tried but it doesn't work!:

    File *fp;
    char lines[100];


    fgets(fp, lines, 100);

    length = strlen(lines)

    for(i=0; i<length-1; i++) // print each individual char
    printf("%s\n", length[i]);

    If the file I read contained:

    abcd

    When I print the contents of the char array line[], I thought
    I would get:

    line[1] = a
    line[2] = b
    line[3] = c
    line[4] = d

    But instead I get:
    line[1] = abcd
    line[2] = bcd
    line[3] = cd
    line[4] = d

    I know in java I have used a 'charAt' function to do this. Does C have something similar in the string.h library? Thanks in advance for any help.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    > printf("%s\n", length[i]);
    Use "%c" to print individual chars
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Stringz
    Guest
    Hi, thanks, but %c didn't work either. Anyother suggestions?

  4. #4
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    I think the problem is somewhere else in your code, as this works -

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
    
    	char lines[100]; 
    	int length,i;
    
    	fgets( lines, 100,stdin); 
    
    	length = strlen(lines); 
    
    	for(i=0; i<length-1; i++) // print each individual char 
    			printf("%c\n", lines[i]); 
    
    	return 0;
    }
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. Counting how many chars in a string
    By tigs in forum C Programming
    Replies: 4
    Last Post: 08-05-2002, 12:25 AM

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