简体   繁体   English

C语言:扫描和打印名称

[英]C Language: Scanning and printing Names

Today, i written a C Programe to scan Two names from keyboard and print it on monitor here it is 今天,我编写了一个C程序来扫描键盘上的两个名称并在监视器上打印它

char b[2],i;

for(i=0;i<2;i++)
{
    scanf("%s",b[i]);
}
for(i=0;i<2;i++)
{
    printf("%s",b[i]);
}

But Output is runtime Error, I am a Beginner to C. What should i do to make it proper program. 但是输出是运行时错误,我是C的初学者。我应该怎么做才能使其成为正确的程序。

First of all, %s is to intake strings , %c is meant to scan individual characters. 首先, %s用于输入字符串%c用于扫描单个字符。

That said, in your case, 也就是说,就您而言,

  1. You did not allocate the spacer for null-terminator in the array. 您没有在数组中为空终止符分配间隔符。
  2. you did not null-terminate the input, either. 您也没有使用null终止输入。 So even if you want, it cannot be used as a sting . 所以,即使你想要的,它不能被用来作为一个刺痛

See what you have declared is wrong char b[2] . 看看您声明的是错误的char b[2] You are scanning string values and your declaration says that you want two characters in b array 您正在扫描字符串值,并且声明说您要在b数组中包含两个字符
If you want to accept two string value than your declaration must be: 如果要接受两个字符串值,则声明必须是:

char *b[1];

Here you can scan the value in the array as: 在这里,您可以按以下方式扫描数组中的值:

*b[0] = "string1";
*b[1] = "string2";

OR 要么
You can use two dimensional array for the storage and then your declaratoin would be: 您可以使用二维数组进行存储,然后声明为:

char b[2][100];

Now here, the 100 specifies the number of characters the string you want to enter and 2 is the number of values of the string you are entering. 现在,这里的100指定要输入的字符串的字符数,而2是输入的字符串的值数。
I hope this will clear your doubts. 我希望这可以消除您的疑虑。

You can correct your code as per given below so that you get correct output. 您可以按照下面的说明更正代码,以便获得正确的输出。

#include<stdio.h>
void main()
{
    char b[2][20];
    int i;
    for(i=0;i<2;i++)
    {
            scanf("%s",b[i]);
    }
    for(i=0;i<2;i++)
    {
            printf("%s\n",b[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM