【问题标题】:Output didn't include all of the characters输出未包含所有字符
【发布时间】:2021-12-21 19:51:00
【问题描述】:

我试图输入一串字符,只分别输出最后一个字符和第一个字符。下面是我正在使用的代码。

#include<stdio.h>
int main(){

    for(int i=0;i<3;i++){
        int n; // length of the string
        char string[101];

        scanf("%d %s", &n, &string);
        fflush(stdin); // sometimes I also use getchar();

        printf("%c%c", string[n+1], string[0]);
    }

    printf("\n");
    
    return 0;
}

我正在使用 for 循环,因为我想输入字符串 3 次,但是当我运行代码时,输​​入不是我所期望的。如果我输入例如

5 abcde

输出

 a //there's space before the a

你能帮我看看我哪里出错了吗?

输入:

5 abcde
6 qwerty
3 ijk

预期输出:

ea
yq
ki

【问题讨论】:

  • C 中的数组使用从 0 开始的索引。所以如果字符串有5个字符,最后一个字符是string[4]
  • 查看here 了解fflush(stdin)
  • 不要让用户就字符串的长度对你撒谎(无论是意外还是故意),您应该使用strlen(string) 来查找字符串的实际长度。
  • 好的,感谢 cmets

标签: c string char


【解决方案1】:

第 11 行:字符串[n+1] -> 字符串[n-1]

【讨论】:

  • 谢谢!我已经改变了它并且它有效。
【解决方案2】:

您的代码中存在一些问题:

在此声明中

scanf("%d %s", &n, &string);

您不需要将&amp; 运算符与string 一起提供。数组名称在表达式中使用时会转换为指向第一个元素的指针(此规则很少有例外)。此外,string 数组的大小为 101 字符,但如果您提供的输入超过 101 字符,scanf() 最终会访问超出其大小的string 数组。当输入大小超过此值时,您应该限制scanf()string 数组中读取的字符不超过100 字符。 (保留剩余的一个字符空间用于scanf() 添加的空终止字符)。为此,您可以在格式说明符中提供宽度修饰符 - %100s

您没有根据用户的输入字符串验证字符串长度输入。如果输入字符串长度大于或小于输入字符串的实际长度会发生什么情况!

fflush(stdin) 是未定义的行为,因为根据标准,fflush 只能用于输出流。

我尝试输入一串字符,只分别输出最后一个和第一个字符。

为此,您不需要将字符串的长度作为用户的输入。使用标准库函数 - strlen()。如果未正确验证,这也将防止您的程序因用户输入错误的长度而出现问题。

把这些放在一起,你可以这样做:

#include <stdio.h>
#include <string.h>

int main (void) {

    for (int i = 0; i < 3 ; i++) {
        char string[101];

        printf ("Enter string:\n");
        scanf("%100s", string);
        printf("Last character: %c, First character: %c\n", string[strlen(string) - 1], string[0]);

        int c;
        /*discard the extra characters, if any*/
        /*For e.g. if user input is very long this will discard the input beyond 100 characters */
        while((c = getchar()) != '\n' && c != EOF)
            /* discard the character */;
    }

    return 0;
}

请注意,scanf(%&lt;width&gt;s, ......) 最多可读取 width 或直到第一个空白字符,以先出现者为准。如果您想在输入中包含空格,您可以在scanf() 中使用适当的转换说明符,或者更好的替代方法是使用fgets() 来自用户的输入。

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多