Store two integers from a String in C -


i trying write program prints 2 numbers string.

for example, string = '20,66' trying break string apart can store '20' , '66' 2 separate variables.

here code working on:

#include <stdio.h>  char line[80];  int main(void) {     // variables     int start_number, end_number;     int i, j;      while(1)     {         printf("enter number: ");         fgets( line, sizeof(line), stdin);          // how find comma         for( i=0; < strlen(line); i++)         {             if(line[i]==',') break;         }          // how find 2 numbers         for(j = 0; j < i; j++)         {             printf("1: %c\n", line[j]);                  }          for(j = + 1; j < strlen(line); j++)         {             printf("2: %c\n", line[j]);         }          if (strcmp(line, "quit\n") == 0)         {             printf("now terminating program...");             break;         }             }    } 

so far, able store single digit variables , reason prints line.

any suggestions or advice appreciated.

quite simple:

const char *text = "20,30"; const char *rest = 0; int first = strtol(text, &rest, 10); // input, pointer remaining string, base (10 = decimal) rest += 1; // skip comma; error prone in case there spaces! int second = strtol(rest, null, 10); // not interested in remaining string, pass null time 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -