#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 部分。
最佳答案
一些问题...
- 索引应该从 0 开始,而不是 1
word
数组必须是 2D(而不是 1D)- 也就是说,您需要一个包含
ROWS
个单词的单词数组,并且每个单词最多可以有LENGTH
个字符. - 一个简单的循环即可获取所有单词,无需任何
if
语句 - 最好使用
fgets
和strlen
而不是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/