Created
June 25, 2013 14:15
-
-
Save plonk/5858779 to your computer and use it in GitHub Desktop.
リスナーさんに教えてもらった strtok で綺麗にかけた奴
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 数を空白くぎりで入力すると和を計算します */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| int calculate_sum(const char *line) | |
| { | |
| int sum = 0; | |
| char *copy = strdup(line); | |
| char *tok = strtok(copy, " "); | |
| do { | |
| sum += atoi(tok); | |
| } while (tok = strtok(NULL, " ")); | |
| free(copy); | |
| return sum; | |
| } | |
| int main() | |
| { | |
| char line[1024]; | |
| printf("入力してください:"); | |
| fgets(line, 1024, stdin); | |
| line[sizeof(line) - 1] = '\0'; | |
| int sum = calculate_sum(line); | |
| printf("%d\n", sum); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment