Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法使用putchar(ch)显示预期结果_C - Fatal编程技术网

无法使用putchar(ch)显示预期结果

无法使用putchar(ch)显示预期结果,c,C,我是C编程新手:D 这是C编程中的编程项目7.1—一种现代方法。例如,输入的名字和姓氏是Lloyd Fosdick,预期结果应该是Fosdick,L。我尝试计算名字中的字符数(本例中为5)。然后,当i>名字的长度时,使用putchar()开始打印,如下面的代码所示 #include <stdio.h> int main(void) { char ch, first_ini; int len1 = 0, i = 0; printf("Enter a first

我是C编程新手:D

这是C编程中的编程项目7.1—一种现代方法。例如,输入的名字和姓氏是Lloyd Fosdick,预期结果应该是Fosdick,L。我尝试计算名字中的字符数(本例中为5)。然后,当i>名字的长度时,使用putchar()开始打印,如下面的代码所示

#include <stdio.h>
int main(void)
{
    char ch, first_ini;
    int len1 = 0, i = 0;
    printf("Enter a first and last name: ");
    ch = getchar();
    first_ini = ch;
    printf("The name is: ");
    while (ch != ' '){
        len1++;
        ch = getchar();
    }
    while (ch != '\n')
    {
        i++;
       if (i <= len1) {
            ch = getchar();
        }
        else {
            putchar(ch);
            ch = getchar();
        }

    }
    printf(", %c", first_ini);
    return 0;
}
#包括
内部主(空)
{
char ch,first_ini;
int len1=0,i=0;
printf(“输入名字和姓氏:”);
ch=getchar();
第一_ini=ch;
printf(“名称为:”);
while(ch!=''){
len1++;
ch=getchar();
}
而(ch!='\n')
{
i++;

如果(i您应该尝试对代码进行以下更改

#include <stdio.h>
int main(void)
{
    char ch, first_ini;
    int len1 = 0, i = 0;
    printf("Enter a first and last name: ");
    ch = getchar();
    first_ini = ch;
    printf("The name is: ");
    while (ch != ' '){
        len1++;
        ch = getchar();
    }
    while (ch != '\n')
    {
        ch = getchar();// get the characters of second word
        if(ch != '\n')
            putchar(ch);// print the characters of second word but avoid newline
    }
    printf(", %c", first_ini);
    return 0;
}
#包括
内部主(空)
{
char ch,first_ini;
int len1=0,i=0;
printf(“输入名字和姓氏:”);
ch=getchar();
第一_ini=ch;
printf(“名称为:”);
while(ch!=''){
len1++;
ch=getchar();
}
而(ch!='\n')
{
ch=getchar();//获取第二个单词的字符
如果(ch!='\n')
putchar(ch);//打印第二个单词的字符,但避免换行
}
printf(“,%c”,第一个ini);
返回0;
}

您的代码的问题是,只有当第二个单词的长度大于第一个单词时,它才开始打印第二个单词的字符。

它似乎在执行您告诉它的操作。它开始在第五个字母处复制姓氏。如果要从开头开始输出姓氏,为什么要让它跳过?啊我明白你的意思:在我调用第二个while循环之前,ch变量已经被分配了一个不同的值。让我稍微修改一下代码,看看是否能得到预期的结果。谢谢@Adarsh Anurag,这就是我所做的,现在我的代码按预期运行。