函数的调用问题,求指导急,

C语言 码拜 7年前 (2017-05-03) 1017次浏览
#include<stdio.h>
void escape(char s[],char t[]);
int main()
{
int c;
char s[20];
char t[20];
printf(“plese input you arr:”);
scanf(“%s”,t);
escape(s,t);
while((c = getchar())!=EOF){
printf(“%s”,s);
}
}

void escape(char s[],char t[]){
int i,j;
for(i = j = 0;t[i] != “\0”;i++){
switch (t[i]){
case “\n”:
s[j++] = “\”;
s[j++] = “n”;
break;
case “\t”:
s[j++] = “\”;
s[j++] = “t”;
break;
default:
s[j++] = t[i];
break;
}
}s[j] = “\0”;
}
高手们好,代码想将字符串t复制到s中,并将换行及制表符以显示的形式出现在s中,但是本人写的这个代码可以编译但是效果不是本人预料中那样,当遇到换行或制表符时,只输出了换行或制表符之前的内容,而且是重复输出,并且debug时候escape函数中j的值并不是每次增加1,这是为什么呢?求高手解答,谢谢了

解决方案

30

引用:
Quote: 引用:
#include<stdio.h>
void escape(char s[],char t[]);
int main()
{
    int c;
    char s[32];
    char t[32];
    printf("plese input you arr:");
    fgets(t, 32, stdin);
    //scanf("%s", t);
    puts(t);
    escape(s, t);
        printf("%s", s);
        /*
    while ((c = getchar()) != EOF) {
        printf("%s",s);
    }
    */
    return 0;
}
void escape(char s[],char t[])
{
    int i, j;
    for(i = j = 0; t[i] != "\0"; i++){
        switch (t[i]){
            case "\n":
                s[j++] = "\";
                s[j++] = "n";
                break;
            case "\t":
                s[j++] = "\";
                s[j++] = "t";
                break;
            default:
                s[j++] = t[i];
                break;
        }
    }
    s[j] = "\0";
}

escape函数没有问题,不过scanf不能输入\t和\n到缓存里。建议使用fgets函数。另外, 之所以会出现多次输出,是原因是while循环导致的。

谢谢!不过为什么scanf不能输入\t 、\n到缓存里呢?

scanf若同时输入多个变量时,是以空格(也可以多个空格)做了间隔区分的,所以\t是多个空格,也就是不能输入的;
另外,标准输入是行缓冲,输入\n标志输入结束;


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明函数的调用问题,求指导急,
喜欢 (0)
[1034331897@qq.com]
分享 (0)