程序在接受C中输入的第二个字符串之前运行 [英] Program Runs before accepting second string in input in C

查看:152
本文介绍了程序在接受C中输入的第二个字符串之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行下面的代码,但程序只接受一个字符串,并立即显示输出而不等待输入第二个字符串。该程序用于2个字符串连接。这里是代码: - $ /

I am trying to run the following code but the program accepts only one string and displays the output immediately without waiting for the second string to be entered. The program is for 2 string concatenation. Here is the code :-

#include <stdio.h>

main()
{
    int i, j, len=0;
    char name[100], abc[100];

    printf("\nPlease Enter String 1 =\t");
    scanf("%[^\n]c",&name);
    printf("\nPlease Enter String 2 =\t");
    scanf("%[^\n]c",&abc);

    for(i=0; name[i]!='\0'; i++)
        len++;
    for(j=0; abc[j]!='\0'; j++)
    {
        len++;
        name[len]=abc[j];
    }

    printf("\nThe Concatenated String Is =\t");
    puts(name);
}


推荐答案

我想建议你不要使用 scanf 。最好使用 fgets 代替。

顺便说一下,你的程序只接受一个字符串并立即显示输出而不等待第二个字符串被输入的是在按下 Enter 后第一个 scanf 留下的 \ n >键。要吃掉这个换行符,你可以在第一个 scanf 之后使用 gatchar()

I would like to suggest you not to use scanf. Better to use fgets instead.
By the way the reason that your program accepts only one string and displays the output immediately without waiting for the second string to be entered is the \n character left behind by the first scanf after pressing the Enter key. To eat up this newline character you may use gatchar() after first scanf.

printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",name);
getchar();
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",abc);  

另外两个错误是:

1.错误的<$ c $增量c> len

for(i=0; name[i]!='\0'; i++)
    len++;
for(j=0; abc[j]!='\0'; j++)
{
    name[len++]=abc[j];  
}   

2。怪异输出的原因是字符串不是NUL终止的。在第二个for循环之后添加此行。

2. Reason for weird output is the string is not NUL terminated. Add this line after second for loop.

name[len] = '\0'; // add this to null terminate your string.  

这是您的工作代码

这篇关于程序在接受C中输入的第二个字符串之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆