Thread: Help with for loop

  1. #1
    Registered User
    Join Date
    Aug 2013

    Help with for loop

    Hey I need some help with a function again. I have a text file I'm reading lines from. Each line has a web address and a encrypted password separated by a comma with a comma also at the end like this;,eYV^RecZi#),,eYV^RecZi#),,eYV^RecZi#),

      FILE *list = fopen("list.txt", "r");
      char input[40] = "";
      fgets(input, 40, list);
      while (fgets(input, 40, list)) {
        input[strcspn(input, "\r\n")] = '\0';
        //printf("%s\n", input);
        int hold = 0;
        char name[40] = "";
        char pass[40] = "";
        for (int i = 0; input[i] != ','; i++){
          name[i] = input[i];
          hold = i;
        hold = hold + 2;
        for (int n = hold; input[n] != ','; n++){
          pass[n] = input[n];
        printf("%s\n", name);
        printf("%s\n", pass);
        printf("%d\n", hold);
    I'm trying to use 2 for loops to separate it back into two separate variables. Passing each character of the web address to a array until a comma is reached. Then the comma is skipped over and a second for loop dose the exact same thing for the password.

    Its working fine for the address but for some reason the password is blank even though its the same for loop just used twice.

    I cant work out why the pass variable is blank when printed at the end.

  2. #2
    Registered User
    Join Date
    Jun 2015
    You need to write characters into pass starting at index 0 but you're starting at hold! One way to fix it:
        pass[n - hold] = input[n];
    This task would normally be done with strtok:
        while (fgets(input, sizeof input, list) != NULL) {
            char *name = strtok(input, ",");
            char *pass = strtok(NULL, ",");
            printf("[%s] [%s]\n", name, pass);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 09-22-2016, 09:08 AM
  2. Replies: 1
    Last Post: 03-28-2015, 08:59 PM
  3. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  4. Replies: 1
    Last Post: 12-26-2011, 07:36 PM
  5. Replies: 23
    Last Post: 04-05-2011, 03:40 PM

Tags for this Thread