ページ 11

配列

Posted: 2015年12月05日(土) 22:27
by momon
文字列を入力し、配列に格納された文字列の奇数番目のみを出力させたいのですが、
奇数番目のみ出力されるようにやってみたのですが出力すらしてくれません。
問題点を教えてください。

よろしくお願いします。

コード:

#include<stdio.h>
#define MAX 100

int a(char *str1, char *str2);

int main(void)
{
	char str1[MAX], str2[MAX];
	int n;

	printf("文字列を入力\n");
	scanf("%s", str1);

	n = a(str1, str2);

	printf("%s\n", str2);
	printf("文字の数は%dです。\n", n);

	return 0;
}

int a(char *str1, char *str2)
{
	int i;

	i = 0;

	while (*(str1 + i) != '\0'){
		if (i % 2 == 1) break;
		*(str2 + i) = *(str1 + i);

	}
	*(str2 + i) = '\0';

	return i;
}

Re: 配列

Posted: 2015年12月05日(土) 22:37
by みけCAT
momon さんが書きました:出力すらしてくれません。
問題点を教えてください。
while文中でiを更新していないので、無限ループになっていますね。

修正案

コード:

#include<stdio.h>
#define MAX 100

int a(char *str1, char *str2);

int main(void)
{
	char str1[MAX], str2[MAX];
	int n;

	printf("文字列を入力\n");
	scanf("%s", str1);

	n = a(str1, str2);

	printf("%s\n", str2);
	printf("文字の数は%dです。\n", n);

	return 0;
}

int a(char *str1, char *str2)
{
	int i;

	i = 0;

	while ((i == 0 || *(str1 + i * 2 - 1) != '\0') && *(str1 + i * 2) != '\0'){
		*(str2 + i) = *(str1 + i * 2);
		i++;

	}
	*(str2 + i) = '\0';

	return i;
}

Re: 配列

Posted: 2015年12月05日(土) 22:47
by box
とりあえずこんな感じ?

コード:

#include <stdio.h>
#define MAX (100)

int a(char *str1, char *str2);

int main(void)
{
    char str1[MAX], str2[MAX];
    int n;

    printf("文字列を入力\n");
    scanf("%s", str1);

    n = a(str1, str2);

    printf("%s\n", str2);
    printf("文字の数は%dです。\n", n);

    return 0;
}

int a(char *str1, char *str2)
{
    int i, j;

    for (i = j = 0; str1[i]; i++) {
        if (i % 2 == 1) str2[j++] = str1[i];
    }
    str2[j] = '\0';
    return j;
}

Re: 配列

Posted: 2015年12月05日(土) 23:00
by みけCAT
オフトピック
boxさんが普通にC言語のコードを投稿している…最近にしては珍しい?
というわけで代わりに書いてみました。

コード:

# coding: UTF-8

def a(str1)
  str2 = str1.chars.each_slice(2).map { |o, _e| o }.join
  [str2.length, str2]
end

puts '文字列を入力'
str1 = gets.chomp
n, str2 = a(str1)
puts str2
printf "文字の数は%dです\n", n