Thread: Struct assign values iterate string

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    4

    Question Struct assign values iterate string

    How can I iterate over the individual characters of a string and copying them one by one to a struct. (in other words, I want to copy char by char into a struct member until a flag is triggered, then move to the next member of the struct i)

    For instance I want to do:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct account {
       char *name;
    };
    
    int main ()
    {
       struct account *acct;
       acct = malloc (40 * sizeof (struct account));
    
       char *str = "Hello World";
       char *a = str;
       char *copy;
       int i = 0;
       while (*a != '\0') {
           acct[i++].name = *a+1; // ?insert 2 char per member
           a++;
       }   
       for(i = 0; i<6; i++)
          printf("%s\n",acct[i].name);
    }
    Output:
    acct[0].name = "He"
    acct[1].name = "ll"
    acct[2].name = "o "
    ...
    Last edited by kaylaneko; 11-16-2010 at 10:28 PM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
    for(a = str;*a != '\0';a++)
    {
      acct[i].name[0] = *a;
      acct[i].name[1] = *(a + 1);
      acct[i++].name[2] = '\0';
      if(*(a + 1) == '\0')
        break;
    }
    Something like that? Why be so difficult though? strncpy() is nice:
    Code:
    int len = strlen(str);
    for(a = str; a - str < len;a += 2)
    {
      strncpy(acct[i].name, a, 2);
      acct[i++].name[2] = '\0';
    }
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    4
    is it possible to use strncpy() and iterate over the string char by char? using the same loop type, the reason I ask this is becuase I need to take different branches based on certain chars found.


    Code:
    while (*a != '\0') {
       // here I need to check for other chars and conditions such as
       if (*a == '@') // do something
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. 3-d array assign string values
    By WaterNut in forum C++ Programming
    Replies: 8
    Last Post: 07-01-2004, 12:02 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM

Tags for this Thread