Hey guys,

I am new to programming in C, I am trying to save "tc" into a variable using for loops. I understand for integers, multiply the result by 10. Is there a similar way to do this for chars?

For integers,

for(j = 0; j < i; j++)
{
	int digit = line[j] - '0';
	start_number = 10 * start_number + digit;
}

For chars,

#include <stdio.h>
#include <string.h> 

int main(int argc, char *argv[])
{

	char line[] = "ta/tb/tc";
	int i, j;
	char a;		
	
	line[strlen(line) - 1] = 0;
	
	// find backslash going in reverse			
	for(i = strlen(line); i > 0; i--)
	{
		if(line[i]=='/') break;
	}				
	printf("%d\n", i);

	// Find tc
	for(j = i + 1; j < strlen(line); j++)
	{	
		printf("%c\n", line[j]);
	}
	
	return 0;
}

look up strtok() for splitting strings.
/*It's not the prettiest thing you will ever see*/

If I understand your question properly, you want to split and store strings rather than integers or single characters. While you could do it manually, that kind of ad hoc parsing is potentially tricky and more verbose than a similar solution using the standard library:

#include <stdio.h>
#include <string.h>

int main()
{
    char src[] = "ta/tb/tc";
    char *tok = strtok(src, "/");
    char dst[3][3];
    size_t i;

    for (i = 0; i < 3 && tok != NULL; i++) {
        dst[i][0] = '\0';
        strncat(dst[i], tok, 2);
        tok = strtok(NULL, "/");
    }

    return 0;
}

Yeah, I was trying to figure out how to do characters rather than integers. I've been looking around online, but I haven't had any luck. Thanks, I will try playing around with the library functions you mentioned.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.