以下是作业描述的一部分:程序必须停止 当用户输入完成单词时接受输入。假设没有单词 超过20个字母。
我必须验证,如果一个单词超过20个字符,您将收到错误消息并且必须重新输入。当我输入完成时,程序应该结束。我不确定如何正确编写这些语句。当我运行它并输入超过20个字符时,它会给我一个错误 - Expression: L("Buffer is too small" &&0)
到目前为止我的代码在这里:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHAR 20
int charcount(char []);
int main()
{
char message[MAXCHAR];
int numofchar;
printf("Enter any word to display how many characters that word has.\nA word CANNOT be more than 20 charatcers long.\n");
printf("When you are finished type the word done.\n");
do
{
printf("\nEnter a word: " );
gets_s(message, MAXCHAR);
numofchar = charcount(message);
while ( numofchar > MAXCHAR)
{
printf("The word enterd is more then 20 characters. Try again.\n");
printf("Enter a word: " );
gets_s(message, MAXCHAR);
}
printf("The word %s has %d characters.\n", (message),numofchar);
} while ( (message,MAXCHAR) != 'done');
printf("\nEnd of program.\n");
system ("PAUSE");
return 0;
}
int charcount (char list[])
{
int i, count = 0;
for(i = 0; list[i] != '\0'; i++)
count++;
return(count);
}
答案 0 :(得分:0)
要检测错误,您只需要检查get_s:
的返回值http://msdn.microsoft.com/en-us/library/5b5x9wc7%28v=vs.90%29.aspx
int main()
{
char message[MAXCHAR], *s;
int numofchar;
...
do
{
printf("\nEnter a word: " );
s = gets_s(message, MAXCHAR);
if (!s) {
<< some error handling code goes here >>
...