【发布时间】:2021-02-17 20:43:56
【问题描述】:
我的代码只需要读取 10 个字符的单词,而不再读取。该代码的目的是检测字谜。如何将 fgets 限制为仅读取 10 个字符,然后显示一条消息 printf(“Word 超过 10 个字符,请重试”)。我的代码在下面,不胜感激。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
// Sorting function to sort words
void lowercase(char *str);
void removespaces(char *str);
int lol(char a[], char b[], int *_lenword1, int *_lenword2);
int main(void){
//Initiating two strings with a maximum limit fo 10 characters
char FirstWord[12];
char SecondWord[12];
/* Console requests input of the first word, fgets reads word of unknown legnth without reading more than buffer allows
Index begins at 0 to use strlen excess allocated characters can be replaced with /0 */
printf("Please enter the first word: \n");
fgets(FirstWord, 12,stdin);
FirstWord[strlen(FirstWord)-1]='\0';
printf("Please enter the second word: \n");
fgets(SecondWord, 12, stdin);
SecondWord[strlen(SecondWord)-1]='\0';
int lenword1 = strlen(FirstWord);
int lenword2 = strlen(SecondWord);
//Relaying strings to functions to convert all characters to lowercase
lowercase(FirstWord);
lowercase(SecondWord);
// Relaying strings to removespaces function so spaces in string are removed
removespaces(FirstWord);
removespaces(SecondWord);
//Decisions
if (lol(FirstWord, SecondWord, &lenword1, &lenword2))
printf("%s and %s are anagrams.\n",FirstWord, SecondWord);
else
printf("%s and %s are not anagrams.\n", FirstWord, SecondWord);
return 0;
}
//Function to sort characters
int lol(char a[], char b[], int *_lenword1, int *_lenword2){
if (*_lenword1 == *_lenword2){
int first[26] = {0}, second[26] = {0}, c=0;
// Calculating frequency of characters of the first string
while (a[c] != '\0') {
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0') {
second[b[c]-'a']++;
c++;
}
// Comparing the frequency of characters
for (c = 0; c < 26; c++){
if (first[c] != second[c]){
return 0;
}
}
return 1;
}
else{ // if different lengths - then they're not anagrams
return 0;
}
}
// Function to convert all letters to lower case (to allow for case sensitivy anagram detection)
void lowercase(char* str){
for (uint8_t i=0; str[i]; i++ ){
str[i]=tolower(str[i]);
}
}
// Function to remove all spaces from a given string
void removespaces( char* str)
{
const char* d = str;
do {
while (*d == ' ') {
++d;
}
} while (*str++ == *d++);
}
【问题讨论】:
-
通常最容易阅读任意长度的单词,然后调用
strlen,如果太长则抱怨。 -
允许像 100 一样的大输入和 检测 超长输入,而不是将输入限制为 10。用户输入是邪恶的。
-
FirstWord[strlen(FirstWord)-1]='\0';不好。如果fgets失败会发生什么?请改用FirstWord[strcspn(FirstWord, "\n")] = '\0';,在确保fgets没有失败。 -
@Someprogrammerdude
FirstWord[strlen(FirstWord)-1]当fgets()读取初始空字符时也是黑客利用。 -
至于你的问题,像
int res = scanf("%10s%c", FirstName, &temp); if (res == EOF || res == 2 && !isspace(temp)) { /* Error, or input too long */}这样的东西怎么样
标签: c