How can I separate an integer into digits using for loop?
eg.
before: 123
after: 1 2 3
anyone can help me with that?
Ricky_v.s_C++
0
Newbie Poster
Recommended Answers
Jump to PostHow can I separate an integer into digits using for loop?
eg.
before: 123
after: 1 2 3
anyone can help me with that?Here is an idea. Convert to char *
Jump to PostHere is an idea. Convert to char *
Bad idea (unless you care to elaborate).
Often using division (/) and remainder (%) operations is used for homework.
Jump to Post#include <string.h> #include <stdio.h> int main() { int num = 123; int i, result; char buff[11], temp[2] = {0, 0}; sprintf(buff, "%d", num); for (i =0; i<strlen(buff); i++) { temp[0] = buff[i]; result = atoi(temp); printf("%d\n", result); } }
Compiled with gcc.
All 9 Replies
andor
25
Posting Whiz in Training
Dave Sinkula
2,398
long time no c
Team Colleague
andor
25
Posting Whiz in Training
Dave Sinkula
2,398
long time no c
Team Colleague
andor
25
Posting Whiz in Training
Dave Sinkula
2,398
long time no c
Team Colleague
andor
25
Posting Whiz in Training
Dave Sinkula
2,398
long time no c
Team Colleague
Ricky_v.s_C++
0
Newbie Poster
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.