字符串不按照它们被分配的方式印刷 [英] Strings are not printed in accordance with the way they are allocated

查看:131
本文介绍了字符串不按照它们被分配的方式印刷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的第一个输出低于code是回来了我的第二个字符串,我的第三个联合。

In the code below my first output is coming back with my second string combined with my third.

#include <stdio.h>

int bandNumber;
char colorOne[];
char colorTwo[];
char colorThree[];

int main(void) {
    printf("How many bands??\n");
    scanf("%d",&bandNumber);
    if(bandNumber == 3) {
        printf("\n\nEnter your first band color: ");
        scanf("%s",colorOne);
        printf("\n\nEnter your second band color: ");
        scanf("%s",colorTwo);
        printf("\n\nEnter your third band color: ");
        scanf("%s",colorThree);
        printf("\n\nBand One: %s",colorOne);
        printf("\n\nBand Two: %s",colorTwo);
        printf("\n\nBand Three: %s\n\n",colorThree);
    }
}

谁能解释的错误,我能做些什么来纠正呢?

Can anyone explain the errors and what I can do to correct them?

推荐答案

中未检测到错误,因为你的编译器的任何警告都没有启用,被忽略或需要一个更好的编译器。这code不被用于读取数据分配空间。

Errors were not detected because either the warnings of your compiler are not enabled, being ignored or need for a better compiler. This code does not allocate space for data being read.

简单的解决方案:使用固定大小的数组和限制用户输入

Simplest solution: used fixed size arrays and limit user input.

#include <stdio.h>

int main(void) {
    char colorOne[80+1];
    printf("How many bands??\n");
    ...
    printf("\n\nEnter your first band color: ");
    if (1 != scanf("%80s", colorOne)) Handle_EOForIOError();
    ...
    printf("\n\nBand One: %s",colorOne);
}

一个更强大的解决方案将使用与fgets()。如果操作系统支持 函数getline() ,考虑这一点。

A more robust solution would use fgets(). If the OS support getline(), consider that.

int main(void) {
    char colorOne[80+1+1];
    printf("How many bands??\n");
    ...
    printf("\n\nEnter your first band color: ");
    if (fgets(colorOne, sizeof colorOne, stdin) == NULL) Handle_EOForIOError();

    // Delete potential ending \n
    size_t len = strlen(colorOne);
    if (len > 0 && colorOne[len-1] == '\n') colorOne[--len] = 0;
    ...
    printf("\n\nBand One: %s",colorOne);
}

防守编码

这篇关于字符串不按照它们被分配的方式印刷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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