简体   繁体   English

验证用户输入字符串

[英]Validating User Input String

Here's part of the description of the assignment: The program must stop accepting input when the user enters the word done. 这是作业说明的一部分:当用户输入完成字时,程序必须停止接受输入。 Assume that no word is more than 20 letters long. 假设单词长度不超过20个字母。

I have to validate that if a word is more than 20 characters thy will get an error message and have to retype again. 我必须验证,如果一个单词超过20个字符,您将收到一条错误消息并必须再次输入。 Also when I type done, the program should end. 同样,当我键入完成时,程序应结束。 Im not sure how to write these statements correctly. 我不确定如何正确编写这些语句。 When I run it and type more then 20 characters it gives me an error - Expression: L("Buffer is too small" &&0) 当我运行它并键入超过20个字符时,它给我一个错误- Expression: L("Buffer is too small" &&0)

Here's my Code so far: 到目前为止,这是我的代码:

#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);

}

To detect an error, you simply need to check the return value of get_s: 要检测错误,您只需要检查get_s的返回值即可:

http://msdn.microsoft.com/en-us/library/5b5x9wc7%28v=vs.90%29.aspx 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