[英]c strcat with pointer
我正在嘗試使用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不起作用。
做了第二次嘗試,即程序找到一個數字,將char存儲在一個變量中,然后嘗試將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的問題。
做了最后一次嘗試,但沒有指針,仍然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
你使它變得比它更難。 你不需要strcat
:
/* Untested. */
char *pont = palavra;
char *pont2 = palavra2;
while (*pont) {
if (isdigit(*pont))
*pont2++ = *pont;
pont++;
}
*pont2 = 0;
你的第三次嘗試幾乎是正確的。
更換
strcat(palavra2, palavra[i]);
同
strncat(palavra2, palavra+i,1);
我正在通過palavra+i
而不是palavra[i]
cos前者是一個進步指針而后者是一個字符而strncat
需要指針
這是一個很好的例子來說明如何連接字符串和字符
另外,請確保始終初始化變量
char palavra[SIZE]="";
char palavra2[SIZE]="";
與您的代碼的問題:(第1版)
1)你做strcat
但*pont
引用單個char,它不是以null結尾的字符串。
2)你做*pont++;
但是* pont是一個值,而不是一個指針。
將此更改為第1版:應該沒問題。
do{
if (isdigit(*pont)){
*pont2=*pont;
pont2++;
}
pont++;
}while (*pont != '\0');
*pont2='\0';
刪除*(取消引用),
strcat(palavra2, pont);
strcat期望char*
不是char
但是這個版本會附加其余的。 你必須創建一個以空字符結尾的字符串。
而*是沒用的
*pont++;
這樣做了
pont++;
現在一下子
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char c2[2] = "a";
char *pont = palavra;
char *pont2 = palavra2;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
c2[0] = *pont;
strcat(palavra2, c2);
}
pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
但是,這太復雜了
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
printf("Insert the string\n");
scanf("%s", palavra);
char *pont = palavra;
char *pont2 = palavra2;
while (true) {
char c = *pont ++;
if (c == 0) break;
if (isdigit(c)){
*pont2++ = c;
}
};
printf("\nThe number is:\n%s\n", palavra2);
return 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.