简体   繁体   English

为什么状态数组的值没有显示在 C 程序的输出中?

[英]Why value of a state array is not showing in the output in C Program?

I'm making a C program in which it'll ask full name and address from the user and the program should give output like this:我正在制作一个 C 程序,它会询问用户的全名和地址,程序应该给出如下输出:

Priya Shah
100,mainstreet
city,subdistrict 
gujarat,382007

But program is giving output like this:但是程序给出了这样的输出:

Priya Shah
100,mainstreet
city,subdistrict
,382007
    #include <stdio.h>

    void main(){
        char fname[10],lname[30];
        char house_no[5],street[40],city[30],taluka[20],state[70]="state",pin[6];
        
        printf("Enter your Full Name: ");
        scanf("%s %s",fname,lname);
    
        printf("Enter your Address: (Format of Address is: HouseNo,Street,City,Taluka,State-pin) ");
        scanf("%s %s %s %s %s %s",house_no,street,city,taluka,state,pin);
    
        printf("%s %s\n%s,%s\n%s,%s\n%

s,%s",fname,lname,house_no,street,city,taluka,state,pin);
}

I have also initialised the state array then also it is not showing in the output我还初始化了状态数组,然后它也没有显示在输出中

I understand your question and i would like to tell that every string has a null character which consume one block of space and in your case .我理解你的问题,我想告诉你,每个字符串都有一个空字符,它消耗一个空间块,在你的情况下。 you wrote pin[6] and you want enter a pin code , like 110010 it is already 6 character but string automatically add null character so in this case you need to replace pin[6] with pin[7]你写了 pin[6] 并且你想输入一个 pin 码,比如 110010 它已经是 6 个字符但是字符串会自动添加空字符所以在这种情况下你需要用 pin[7] 替换 pin[6]

thank you.......谢谢你.......

pin[6] is too short to store 6-character strings like 382007 . pin[6]太短,无法存储382007等 6 个字符的字符串。 A room for terminating null-character is required.需要一个用于终止空字符的空间。 It looks like st happened to be placed after pin and its data is destroyed due to the out-of-range write.看起来st恰好放在pin之后,并且由于超出范围的写入,它的数据被破坏了。

Allocate enough elements and specify the maximum number of characters to read to prevent buffer overrun.分配足够的元素并指定要读取的最大字符数以防止缓冲区溢出。 Also you should check the return values of scanf() to check if it succeeded to read all required things.您还应该检查scanf()的返回值以检查它是否成功读取了所有必需的内容。

#include <stdio.h>

int main(void){
    char fname[10],lname[30];
    char house_no[5],street[40],city[30],taluka[20],st[70]="state",pin[20];
    
    printf("Enter your Full Name: ");
    if (scanf("%9s %29s",fname,lname) != 2){
        fputs("read error\n", stderr);
        return 1;
    }

    printf("Enter your Address: (Format of Address is: HouseNo,Street,City,Taluka,State-pin) ");
    if(scanf("%4s %39s %29s %19s %69s %19s",house_no,street,city,taluka,st,pin) != 6){
        fputs("read error\n", stderr);
        return 1;
    }

    printf("%s %s\n%s,%s\n%s,%s\n%s,%s",fname,lname,house_no,street,city,taluka,st,pin);
}

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

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