Skip to content

Instantly share code, notes, and snippets.

@plonk
Created June 25, 2013 14:15
Show Gist options
  • Select an option

  • Save plonk/5858779 to your computer and use it in GitHub Desktop.

Select an option

Save plonk/5858779 to your computer and use it in GitHub Desktop.
リスナーさんに教えてもらった strtok で綺麗にかけた奴
/* 数を空白くぎりで入力すると和を計算します */
#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