0

以下是对分配的部分描述: 当用户输入单词 done 时,程序必须停止接受输入。假设没有一个词的长度超过 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);

}
4

1 回答 1

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 >>
        ...
于 2013-11-02T22:25:49.557 回答