c - 我正在尝试创建一个函数来接受用户输入的回文。为什么我输入一个数组后,它会自动输入其余的数组?

标签 c loops for-loop while-loop syntax

#include<stdio.h>
#include<string.h>
#define ROWS 6
#define LENGTH 30

int main (void)
{

    int wordcount[ROWS]; // Incraments word count. i.e. Word 1, Word 2, Word 3...
    char word[LENGTH]; // Stores users string

    for(int i = 1; i < ROWS; i++)
    {
        if(i == 1)
        {
            printf("Word %d: ", i);
            scanf("%d %s", &wordcount[i], &word[0]); // Input ends here. Prints out the rest of the array with "no" values.
            i++;
        }
        if(i == 2)
        {
            printf("Word %d: ", i);
            scanf("%d %s", &wordcount[i], &word[1]);
            i++;
        }
        if(i == 3)
        {
            printf("Word %d: ", i);
            scanf("%d %s", &wordcount[i], &word[2]);
            i++;
        }
        if(i == 4)
        {
            printf("Word %d: ", i);
            scanf("%d %s", &wordcount[i], &word[3]);
            i++;
        }
        if(i == 5)
        {
            printf("Word %d: ", i);
            scanf("%d %s", &wordcount[i], &word[4]);
        }
        break;

    }

return 0;

}

我尝试了多个循环、更改语法和位置,但对我来说没有任何意义了。除了 scanf()printf()fgets() 之外,我不允许使用指针、全局变量或任何其他 LIB 函数,或strlen()。我必须创建多个函数来获取用户输入、反转字符串并确定它是否是回文...但我似乎无法完成第 1 部分。

最佳答案

一些问题...

  1. 索引应该从 0 开始,而不是 1
  2. word 数组必须是 2D(而不是 1D)
  3. 也就是说,您需要一个包含 ROWS 个单词的单词数组,并且每个单词最多可以有 LENGTH 个字符.
  4. 一个简单的循环即可获取所有单词,无需任何 if 语句
  5. 最好使用 fgetsstrlen 而不是 scanf 来提示用户进行输入

这是重构后的代码:

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

#define ROWS        5
#define LENGTH      100

int
main(void)
{

    // length of each word
    int wordcount[ROWS];

    // Stores users string
    char word[ROWS][LENGTH];

    for (int i = 0; i < ROWS; i++) {
        // prompt the user
        printf("Word %d: ", i + 1);
        fflush(stdout);

        // get the line with the word
        if (fgets(word[i],LENGTH,stdin) == NULL)
            break;

        // get the word length
        size_t len = strlen(word[i]);

        // strip newline
        if ((len > 0) && (word[i][len - 1] == '\n')) {
            word[i][len - 1] = 0;
            --len;
        }

        // save the length
        wordcount[i] = len;
    }

    // print the words
    for (int i = 0;  i < ROWS;  ++i)
        printf("Word %d is %d bytes: '%s'\n",i + 1,wordcount[i],word[i]);

    return 0;
}

关于c - 我正在尝试创建一个函数来接受用户输入的回文。为什么我输入一个数组后,它会自动输入其余的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74397333/

相关文章:

c - 如何在 C 中创建结构的 "objects"

c - 未知类型名称 BOOL 链接头文件编译错误

c++ - 了解循环不变量

python - 如何定义通过另一个函数内的 for 循环创建的全局变量?

c - 2D字符串数组遇到具有多个空格或数字的单词时存储 '\0'

c - 搜索完整的哈希表

c++ - 如何在循环外设置初始值? C++

java - 如何禁用除特定输入之外的键盘输入,或在使用错误的输入时显示错误?

java - 长循环计数器似乎效率很低

c++ - 在基于C++范围的循环中使用&运算符..令人困惑