簡體   English   中英

驗證用戶輸入字符串

[英]Validating User Input String

這是作業說明的一部分:當用戶輸入完成字時,程序必須停止接受輸入。 假設單詞長度不超過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);

}

要檢測錯誤,您只需要檢查get_s的返回值即可:

http://msdn.microsoft.com/zh-CN/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 >>
        ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM