限制输入字符串字符
Limiting input string characters
我正在尝试编写一个简单的代码,用户必须在其中输入一个字符串,但如果该字符串超过五个字符,它应该打印出一个错误和 return -1。
我使用 fgets 获取输入并使用 strlen 计算字符串的长度。
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
int main()
{
char a[5];
int length = 0;
printf("Enter a string to calculate it's length\n");
fgets(a,5,stdin);
length = strlen(a)-1; // don't want the '\n' to be counted
if(length > 5){
printf("error");
}
printf("string length %d\n",length);
return 0;
}
当我输入超过 5 个字符的字符串时,它不会打印出错误,它只会打印出字符串大小为三。
有人可以给我提示吗?
提前致谢。
fgets(a,5,stdin);
fgets
始终读取大小为 1 的字符。
读取在 EOF 或换行符后停止。
所以,它只读取 4 个字符。
length = strlen(a)-1; // 4-1 = 3
使用strchr
检查换行符。如果输入中没有换行符,读取字符直到找到换行符清除输入缓冲区并重试。
#include <stdio.h>
#include <string.h>
int main( void) {
char a[7];//five characters, a newline and a zero terminator
int toolong = 0;
do {
if ( toolong) {
printf ( "too many characters. try again\n");
}
toolong = 0;
printf ( "enter up to five characters.\n");
if ( fgets ( a, sizeof a, stdin)) {
while ( ! strchr ( a, '\n')) {//check for newline
toolong = 1;
fgets ( a, sizeof a, stdin);//read more characters
}
}
else {
fprintf ( stderr, "fgets EOF\n");
return 0;
}
} while ( toolong);
return 0;
}
我正在尝试编写一个简单的代码,用户必须在其中输入一个字符串,但如果该字符串超过五个字符,它应该打印出一个错误和 return -1。 我使用 fgets 获取输入并使用 strlen 计算字符串的长度。
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
int main()
{
char a[5];
int length = 0;
printf("Enter a string to calculate it's length\n");
fgets(a,5,stdin);
length = strlen(a)-1; // don't want the '\n' to be counted
if(length > 5){
printf("error");
}
printf("string length %d\n",length);
return 0;
}
当我输入超过 5 个字符的字符串时,它不会打印出错误,它只会打印出字符串大小为三。
有人可以给我提示吗?
提前致谢。
fgets(a,5,stdin);
fgets
始终读取大小为 1 的字符。
读取在 EOF 或换行符后停止。 所以,它只读取 4 个字符。
length = strlen(a)-1; // 4-1 = 3
使用strchr
检查换行符。如果输入中没有换行符,读取字符直到找到换行符清除输入缓冲区并重试。
#include <stdio.h>
#include <string.h>
int main( void) {
char a[7];//five characters, a newline and a zero terminator
int toolong = 0;
do {
if ( toolong) {
printf ( "too many characters. try again\n");
}
toolong = 0;
printf ( "enter up to five characters.\n");
if ( fgets ( a, sizeof a, stdin)) {
while ( ! strchr ( a, '\n')) {//check for newline
toolong = 1;
fgets ( a, sizeof a, stdin);//read more characters
}
}
else {
fprintf ( stderr, "fgets EOF\n");
return 0;
}
} while ( toolong);
return 0;
}