私はポインタとstrcatをCから使用しようとしています。これは私の学習プロセスの一部です。ポインタ付きstrcat
アイデアは、ユーザーが数字を含む文字列を入力し、出力が数字のみを返すという考えです。 したがって、ユーザが te12abc
を入力すると、出力は12
になります。
これが私の最初の試みである:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 10
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char *pont = palavra;
char *pont2 = palavra2;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
strcat(palavra2, *pont);
}
*pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
私は期待通りにポインタが動作していることを信じているが、strcatのが動作していない理由を理解することはできません。
プログラムが数値を見つけて、その変数を1つの変数に格納し、その変数でstrcatを使用しようとすると、もう一度試みます。コードは次のとおりです。
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char temp;
char *pont = palavra;
char * pont2 = &temp;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
temp = *pont;
strcat(palavra2, pont2);
}
*pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
もう一度、strcatで問題が発生します。
最後に1つ試みたが、ポインタがなくてもstrcatが機能しない。コードは次のとおりです。
int main()
{
int i = 0;
char palavra[SIZE];
char palavra2[SIZE];
char temp;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(palavra[i])){
temp = palavra[i];
strcat(palavra2, palavra[i]);
}
i++;
}while (palavra[i] != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
正しい方向を教えてください。今私はより多くの何を行うことができます。..
よろしく、
favolas
小さな問題は、私が理解し、OPはので、例えば、文字列内のすべての数字を追加したいと思います"a1b2c3d"は3つの追加を行います。 'while(* pont){if(isdigit(* pont)){* pont2 ++ = * pont; } ++ pont; } * pont2 = 0; '、と思います。 –
@ダニエルフィッシャーああ、私は参照してください。公正で十分です、ありがとう:-) – cnicutar
@cnicutarありがとうこれは動作しますが、 'te1te2te3te4te5'を挿入するとプログラムがクラッシュします。文字列のサイズが10未満であると定義されていると思われます。 – Favolas