确定输入是仅包含数字或q,使用返回的字符串和malloc。

huangapple go评论76阅读模式
英文:

determine if input is only digits or q using a returned string and malloc

问题

我想创建一个自己的函数,在这个函数中,我输入一个值,然后我的函数将确定我是否只输入了数字(例如23412),或者是否只输入了一个字母q。其他任何输入都应被视为无效输入。请注意,"242q42"、"5435q"或"qq"都应视为无效输入。我相信我已经成功创建了一个能够判断我是否只输入了数字的工作函数,但我不确定如何使字母q的检查工作。以下是我的代码(如果您发现错误、效率低下的代码或其他改进之处,请评论):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char *readLine(int nr) {
    int ch, i = 0;
    char *string;
    string = malloc(nr);

    while ((ch = getchar()) != '\n') {
        if (i < nr && isdigit(ch) != 0) {
            string[i++] = ch;
        } else if (i == 0 && ch == 'q') { // Check for 'q' as the first and only character
            string[i++] = ch;
        } else {
            free(string); // Free memory before returning NULL
            return NULL;
        }
    }
    string[i] = '
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char *readLine(int nr) {
    int ch, i = 0;
    char *string;
    string = malloc(nr);

    while ((ch = getchar()) != '\n') {
        if (i < nr && isdigit(ch) != 0) {
            string[i++] = ch;
        } else if (i == 0 && ch == 'q') { // Check for 'q' as the first and only character
            string[i++] = ch;
        } else {
            free(string); // Free memory before returning NULL
            return NULL;
        }
    }
    string[i] = '\0';

    return string;
}

int main(void) {
    int number;

    printf("Enter number: ");
    char *p = readLine(100);

    if (p == NULL) {
        printf("Invalid input!\n");
    } else {
        number = atoi(p);
        printf("Number as int is %d ", number);
    }
    free(p);

    return 0;
}
'
;
return string; } int main(void) { int number; printf("Enter number: "); char *p = readLine(100); if (p == NULL) { printf("Invalid input!\n"); } else { number = atoi(p); printf("Number as int is %d ", number); } free(p); return 0; }

我在代码中添加了一个检查,以确保字母q作为第一个且唯一字符时也被接受。其他无效输入会导致函数返回NULL,并释放先前分配的内存。希望这可以满足您的要求。

英文:

I want to create my own function in which I enter an input, and then my function will determine if I only entered digits (such as 23412) or if I entered only a single q. Everything else should be counted as invalid input. Note that "242q42", "5435q" or "qq" should be considered invalid input. I believe I managed to create a working function that can decide if I only entered digits, but I am not sure how I should do to get the q thing working. Here is my code(please comment if you see mistakes or inefficient code or other improvements I can make):

char *readLine(int nr) {
   int ch, i=0;
   char *string;
   string = malloc(nr);

   while((ch = getchar()) != &#39;\n&#39;) {
       if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
          string[i++]=ch;
       }
       else {
          string=NULL;
          return string;
       }
   }
   string[i]=&#39;
char *readLine(int nr) {
int ch, i=0;
char *string;
string = malloc(nr);
while((ch = getchar()) != &#39;\n&#39;) {
if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
string[i++]=ch;
}
else {
string=NULL;
return string;
}
}
string[i]=&#39;\0&#39;;
return string;
} 
int main(void) {
int number;
printf(&quot;Enter number: &quot;);
char *p=readLine(100);
if(p==NULL) {
printf(&quot;Invalid input!\n&quot;);
}
else {
number=atoi(p);
printf(&quot;Number as int is %d &quot;, number);
}
free(p);
return 0;
}
&#39;; return string; } int main(void) { int number; printf(&quot;Enter number: &quot;); char *p=readLine(100); if(p==NULL) { printf(&quot;Invalid input!\n&quot;); } else { number=atoi(p); printf(&quot;Number as int is %d &quot;, number); } free(p); return 0; }

答案1

得分: 2

在代码中添加另一个 if 语句,检查 q 是否是第一个字符,并将其添加到 string

在分配 NULL 之前,你还需要在调用者中检查 q,以确保在尝试调用 atoi() 之前释放 string,否则会有内存泄漏。

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

char *readLine(int nr) {
    int ch, i = 0, q_entered = 0;
    char *string;
    string = malloc(nr);

    while ((ch = getchar()) != '\n') {
        if (i < nr && !q_entered && isdigit(ch) != 0) {
            string[i++] = ch;
        } else if (i == 0 && ch == 'q') {
            string[i++] = ch;
            q_entered = 1;
        } else {
            free(string);
            return NULL;
        }
    }
    string[i] = '
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

char *readLine(int nr) {
    int ch, i = 0, q_entered = 0;
    char *string;
    string = malloc(nr);

    while ((ch = getchar()) != '\n') {
        if (i < nr && !q_entered && isdigit(ch) != 0) {
            string[i++] = ch;
        } else if (i == 0 && ch == 'q') {
            string[i++] = ch;
            q_entered = 1;
        } else {
            free(string);
            return NULL;
        }
    }
    string[i] = '\0';

    return string;
}

int main(void) {
    int number;

    printf("Enter number: ");
    char *p = readLine(100);

    if (p == NULL) {
        printf("Invalid input!\n");
    } else if (strcmp(p, "q") == 0) {
        printf("Quitting\n");
    } else {
        number = atoi(p);
        printf("Number as int is %d\n", number);
    }
    free(p);

    return 0;
}
'
;
return string; } int main(void) { int number; printf("Enter number: "); char *p = readLine(100); if (p == NULL) { printf("Invalid input!\n"); } else if (strcmp(p, "q") == 0) { printf("Quitting\n"); } else { number = atoi(p); printf("Number as int is %d\n", number); } free(p); return 0; }

尽管如此,更好的设计通常是将输入代码与解析输入的代码分离开来。readLine() 应该只返回以任何格式存储的行,你可以拥有一个单独的 allDigits() 函数来检查是否满足特定条件。

英文:

Add another if statement that checks for q as the first character, and add it to string.

You also need to free(string) before assigning NULL, otherwise you have a memory leak.

In the caller, check for q before trying to call atoi().

#include &lt;stdio.h&gt;
#include &lt;ctype.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

char *readLine(int nr) {
	int ch, i=0, q_entered = 0;
	char *string;
	string = malloc(nr);

	while((ch = getchar()) != &#39;\n&#39;) {
		if(i&lt;nr &amp;&amp; !q_entered &amp;&amp; isdigit(ch)!=0) {
			string[i++]=ch;
		} else if (i == 0 &amp;&amp; ch == &#39;q&#39;) {
			string[i++] = ch;
			q_entered = 1;
		} else {
			free(string);
			return NULL;
		}
	}
	string[i]=&#39;
#include &lt;stdio.h&gt;
#include &lt;ctype.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
char *readLine(int nr) {
int ch, i=0, q_entered = 0;
char *string;
string = malloc(nr);
while((ch = getchar()) != &#39;\n&#39;) {
if(i&lt;nr &amp;&amp; !q_entered &amp;&amp; isdigit(ch)!=0) {
string[i++]=ch;
} else if (i == 0 &amp;&amp; ch == &#39;q&#39;) {
string[i++] = ch;
q_entered = 1;
} else {
free(string);
return NULL;
}
}
string[i]=&#39;\0&#39;;
return string;
}
int main(void) {
int number;
printf(&quot;Enter number: &quot;);
char *p=readLine(100);
if(p==NULL) {
printf(&quot;Invalid input!\n&quot;);
} else if (strcmp(p, &quot;q&quot;) == 0) {
printf(&quot;Quitting\n&quot;);
} else {
number=atoi(p);
printf(&quot;Number as int is %d\n&quot;, number);
}
free(p);
return 0;
}
&#39;; return string; } int main(void) { int number; printf(&quot;Enter number: &quot;); char *p=readLine(100); if(p==NULL) { printf(&quot;Invalid input!\n&quot;); } else if (strcmp(p, &quot;q&quot;) == 0) { printf(&quot;Quitting\n&quot;); } else { number=atoi(p); printf(&quot;Number as int is %d\n&quot;, number); } free(p); return 0; }

That said, it's usually better design to separate the input code from the code that parses the input. readLine() should just return the line in any format, and you should have a separate allDigits() function that checks for this.

答案2

得分: 1

在你的问题中,你说明了你希望输入只包括以下情况之一:

  • 仅由数字组成,或
  • 仅包括单个字符 &quot;q&quot;

否则,输入是无效的,应该被拒绝。

然而,在评论部分,你提到输入字符串 &quot;0&quot; 也应该被拒绝。相反,你希望输入在 1 到某个最大值的范围内。

在这种情况下,使用函数 isdigit 来确定输入 &quot;0&quot; 是否有效并没有意义,因为它会报告该输入有效,尽管你希望将其作为无效输入拒绝。

因此,我建议你首先使用函数 fgets 读取整行,然后检查该行的内容。如果该行只包含单个字符 q,那么你就知道输入是有效的。否则,你可以使用函数 strtol 尝试将输入转换为整数。

如果转换失败,你就知道输入是无效的。

然而,如果转换成功,你可以进行进一步的检查,以确定转换后的整数是否在所需范围内,例如是否在 120 的范围内。

以下是一个示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20

void get_line_from_user( const char prompt[], char buffer[], int buffer_size );

int main( void )
{
    // ... (同上提供的代码)
}

// get_line_from_user 函数的翻译部分见下方

此程序具有以下行为:

请输入一个数字:242q42
错误:未能将所有非空白字符转换为整数!
请输入一个数字:5435q
错误:未能将所有非空白字符转换为整数!
请输入一个数字:qq
错误:无法将输入转换为整数!
请输入一个数字:q
输入有效,用户输入了“q”。
请输入一个数字:50000000000000000000000000
错误:输入超出了 long int 的范围!
请输入一个数字:-23
错误:输入必须在 1 到 20 的范围内。
请输入一个数字:0
错误:输入必须在 1 到 20 的范围内。
请输入一个数字:22
错误:输入必须在 1 到 20 的范围内。
请输入一个数字:17
输入有效!用户输入了 17。

要更改允许的范围,你可以修改程序中的以下行:

#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20

希望对你有所帮助!

英文:

In your question, you stated that you wanted the input to consist either of

  • only digits, or
  • only the single character &quot;q&quot;.

Otherwise, the input is invalid and should be rejected.

However, in the comments section, you stated that the input string &quot;0&quot; should also be rejected. Instead, you want the input to be in the range of 1 to a certain maximum value.

In that case, it is not meaningful to use the function isdigit to determine whether the input &quot;0&quot; is valid, because it will report that input as valid, although you want that input to be rejected as invalid.

For this reason, I recommend that you first read an entire line using the function fgets, and then inspect the content of that line. If that line consists of the single character q, then you know the input is valid. Otherwise, you can use the function strtol in order to attempt to convert the input to an integer.

If this conversion fails, then you will know that the input is invalid.

However, if the conversion succeeds, you can then perform one further check, to determine whether the converted integer is in the desired range, for example whether it is in the range 1 to 20.

Here is an example:

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;
#include &lt;errno.h&gt;

#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20

void get_line_from_user( const char prompt[], char buffer[], int buffer_size );

int main( void )
{
    char line[200], *p;
    long num;

    //read exactly one line of input from the user
    get_line_from_user(
        &quot;Please enter a number: &quot;,
        line, sizeof line
    );

    //determine whether the user entered `&quot;q&quot;` as input
    if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;
#include &lt;errno.h&gt;
#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20
void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
int main( void )
{
char line[200], *p;
long num;
//read exactly one line of input from the user
get_line_from_user(
&quot;Please enter a number: &quot;,
line, sizeof line
);
//determine whether the user entered `&quot;q&quot;` as input
if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
{
printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
exit( EXIT_SUCCESS );
}
//attempt to convert input to a number
errno = 0;
num = strtol( line, &amp;p, 10 );
//verify that at least one character was converted
if ( p == line )
{
printf( &quot;Error: Unable to convert input to integer!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that input is not too small or too large to be
//representable as a `long int`
if ( errno == ERANGE )
{
printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that either all characters were converted or that all
//remaining characters are whitespace characters, so that input
//such as &quot;242q42&quot; gets rejected
for ( ; *p != &#39;\0&#39;; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
exit( EXIT_FAILURE );
}
}
//verify that the converted integer is in the desired range
if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
{
printf(
&quot;Error: Input must be in the range %d to %d.\n&quot;,
MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
);
exit( EXIT_FAILURE );
}
//everything went ok, so print the result
printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
return EXIT_SUCCESS;
}
//This function will read exactly one line of input from the
//user. It will remove the newline character, if it exists. If
//the line is too long to fit in the buffer, then the function
//will automatically reprompt the user for input. On failure,
//the function will never return, but will print an error
//message and call &quot;exit&quot; instead.
void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
{
for (;;) //infinite loop, equivalent to while(1)
{
char *p;
//prompt user for input
fputs( prompt, stdout );
//attempt to read one line of input
if ( fgets( buffer, buffer_size, stdin ) == NULL )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
//attempt to find newline character
p = strchr( buffer, &#39;\n&#39; );
//make sure that entire line was read in (i.e. that
//the buffer was not too small to store the entire line)
if ( p == NULL )
{
int c;
//a missing newline character is ok if the next
//character is a newline character or if we have
//reached end-of-file (for example if the input is
//being piped from a file or if the user enters
//end-of-file in the terminal itself)
if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
{
if ( c == EOF )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
printf( &quot;Input was too long to fit in buffer!\n&quot; );
//discard remainder of line
do
{
c = getchar();
if ( c == EOF )
{
//this error message will be printed if either
//a stream error or an unexpected end-of-file
//is encountered
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
} while ( c != &#39;\n&#39; );
//reprompt user for input by restarting loop
continue;
}
}
else
{
//remove newline character by overwriting it with
//null character
*p = &#39;\0&#39;;
}
//input was ok, so break out of loop
break;
}
}
&#39; ) { printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; ); exit( EXIT_SUCCESS ); } //attempt to convert input to a number errno = 0; num = strtol( line, &amp;p, 10 ); //verify that at least one character was converted if ( p == line ) { printf( &quot;Error: Unable to convert input to integer!\n&quot; ); exit( EXIT_FAILURE ); } //verify that input is not too small or too large to be //representable as a `long int` if ( errno == ERANGE ) { printf( &quot;Error: Input is outside the range of a long int!\n&quot; ); exit( EXIT_FAILURE ); } //verify that either all characters were converted or that all //remaining characters are whitespace characters, so that input //such as &quot;242q42&quot; gets rejected for ( ; *p != &#39;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;
#include &lt;errno.h&gt;
#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20
void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
int main( void )
{
char line[200], *p;
long num;
//read exactly one line of input from the user
get_line_from_user(
&quot;Please enter a number: &quot;,
line, sizeof line
);
//determine whether the user entered `&quot;q&quot;` as input
if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
{
printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
exit( EXIT_SUCCESS );
}
//attempt to convert input to a number
errno = 0;
num = strtol( line, &amp;p, 10 );
//verify that at least one character was converted
if ( p == line )
{
printf( &quot;Error: Unable to convert input to integer!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that input is not too small or too large to be
//representable as a `long int`
if ( errno == ERANGE )
{
printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that either all characters were converted or that all
//remaining characters are whitespace characters, so that input
//such as &quot;242q42&quot; gets rejected
for ( ; *p != &#39;\0&#39;; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
exit( EXIT_FAILURE );
}
}
//verify that the converted integer is in the desired range
if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
{
printf(
&quot;Error: Input must be in the range %d to %d.\n&quot;,
MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
);
exit( EXIT_FAILURE );
}
//everything went ok, so print the result
printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
return EXIT_SUCCESS;
}
//This function will read exactly one line of input from the
//user. It will remove the newline character, if it exists. If
//the line is too long to fit in the buffer, then the function
//will automatically reprompt the user for input. On failure,
//the function will never return, but will print an error
//message and call &quot;exit&quot; instead.
void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
{
for (;;) //infinite loop, equivalent to while(1)
{
char *p;
//prompt user for input
fputs( prompt, stdout );
//attempt to read one line of input
if ( fgets( buffer, buffer_size, stdin ) == NULL )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
//attempt to find newline character
p = strchr( buffer, &#39;\n&#39; );
//make sure that entire line was read in (i.e. that
//the buffer was not too small to store the entire line)
if ( p == NULL )
{
int c;
//a missing newline character is ok if the next
//character is a newline character or if we have
//reached end-of-file (for example if the input is
//being piped from a file or if the user enters
//end-of-file in the terminal itself)
if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
{
if ( c == EOF )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
printf( &quot;Input was too long to fit in buffer!\n&quot; );
//discard remainder of line
do
{
c = getchar();
if ( c == EOF )
{
//this error message will be printed if either
//a stream error or an unexpected end-of-file
//is encountered
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
} while ( c != &#39;\n&#39; );
//reprompt user for input by restarting loop
continue;
}
}
else
{
//remove newline character by overwriting it with
//null character
*p = &#39;\0&#39;;
}
//input was ok, so break out of loop
break;
}
}
&#39;; p++ ) { if ( !isspace( (unsigned char)*p ) ) { printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; ); exit( EXIT_FAILURE ); } } //verify that the converted integer is in the desired range if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER ) { printf( &quot;Error: Input must be in the range %d to %d.\n&quot;, MIN_INPUT_NUMBER, MAX_INPUT_NUMBER ); exit( EXIT_FAILURE ); } //everything went ok, so print the result printf( &quot;Input was valid! User entered %ld.\n&quot;, num ); return EXIT_SUCCESS; } //This function will read exactly one line of input from the //user. It will remove the newline character, if it exists. If //the line is too long to fit in the buffer, then the function //will automatically reprompt the user for input. On failure, //the function will never return, but will print an error //message and call &quot;exit&quot; instead. void get_line_from_user( const char prompt[], char buffer[], int buffer_size ) { for (;;) //infinite loop, equivalent to while(1) { char *p; //prompt user for input fputs( prompt, stdout ); //attempt to read one line of input if ( fgets( buffer, buffer_size, stdin ) == NULL ) { printf( &quot;Error reading from input!\n&quot; ); exit( EXIT_FAILURE ); } //attempt to find newline character p = strchr( buffer, &#39;\n&#39; ); //make sure that entire line was read in (i.e. that //the buffer was not too small to store the entire line) if ( p == NULL ) { int c; //a missing newline character is ok if the next //character is a newline character or if we have //reached end-of-file (for example if the input is //being piped from a file or if the user enters //end-of-file in the terminal itself) if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) ) { if ( c == EOF ) { printf( &quot;Error reading from input!\n&quot; ); exit( EXIT_FAILURE ); } printf( &quot;Input was too long to fit in buffer!\n&quot; ); //discard remainder of line do { c = getchar(); if ( c == EOF ) { //this error message will be printed if either //a stream error or an unexpected end-of-file //is encountered printf( &quot;Error reading from input!\n&quot; ); exit( EXIT_FAILURE ); } } while ( c != &#39;\n&#39; ); //reprompt user for input by restarting loop continue; } } else { //remove newline character by overwriting it with //null character *p = &#39;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;
#include &lt;errno.h&gt;
#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20
void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
int main( void )
{
char line[200], *p;
long num;
//read exactly one line of input from the user
get_line_from_user(
&quot;Please enter a number: &quot;,
line, sizeof line
);
//determine whether the user entered `&quot;q&quot;` as input
if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
{
printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
exit( EXIT_SUCCESS );
}
//attempt to convert input to a number
errno = 0;
num = strtol( line, &amp;p, 10 );
//verify that at least one character was converted
if ( p == line )
{
printf( &quot;Error: Unable to convert input to integer!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that input is not too small or too large to be
//representable as a `long int`
if ( errno == ERANGE )
{
printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
exit( EXIT_FAILURE );
}
//verify that either all characters were converted or that all
//remaining characters are whitespace characters, so that input
//such as &quot;242q42&quot; gets rejected
for ( ; *p != &#39;\0&#39;; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
exit( EXIT_FAILURE );
}
}
//verify that the converted integer is in the desired range
if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
{
printf(
&quot;Error: Input must be in the range %d to %d.\n&quot;,
MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
);
exit( EXIT_FAILURE );
}
//everything went ok, so print the result
printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
return EXIT_SUCCESS;
}
//This function will read exactly one line of input from the
//user. It will remove the newline character, if it exists. If
//the line is too long to fit in the buffer, then the function
//will automatically reprompt the user for input. On failure,
//the function will never return, but will print an error
//message and call &quot;exit&quot; instead.
void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
{
for (;;) //infinite loop, equivalent to while(1)
{
char *p;
//prompt user for input
fputs( prompt, stdout );
//attempt to read one line of input
if ( fgets( buffer, buffer_size, stdin ) == NULL )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
//attempt to find newline character
p = strchr( buffer, &#39;\n&#39; );
//make sure that entire line was read in (i.e. that
//the buffer was not too small to store the entire line)
if ( p == NULL )
{
int c;
//a missing newline character is ok if the next
//character is a newline character or if we have
//reached end-of-file (for example if the input is
//being piped from a file or if the user enters
//end-of-file in the terminal itself)
if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
{
if ( c == EOF )
{
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
printf( &quot;Input was too long to fit in buffer!\n&quot; );
//discard remainder of line
do
{
c = getchar();
if ( c == EOF )
{
//this error message will be printed if either
//a stream error or an unexpected end-of-file
//is encountered
printf( &quot;Error reading from input!\n&quot; );
exit( EXIT_FAILURE );
}
} while ( c != &#39;\n&#39; );
//reprompt user for input by restarting loop
continue;
}
}
else
{
//remove newline character by overwriting it with
//null character
*p = &#39;\0&#39;;
}
//input was ok, so break out of loop
break;
}
}
&#39;; } //input was ok, so break out of loop break; } }

This program has the following behavior:

Please enter a number: 242q42
Error: Not all non-whitespace characters were converted!
Please enter a number: 5435q
Error: Not all non-whitespace characters were converted!
Please enter a number: qq
Error: Unable to convert input to integer!
Please enter a number: q
Input is valid, user entered &quot;q&quot;.
Please enter a number: 50000000000000000000000000
Error: Input is outside the range of a long int!
Please enter a number: -23
Error: Input must be in the range 1 to 20.
Please enter a number: 0
Error: Input must be in the range 1 to 20.
Please enter a number: 22
Error: Input must be in the range 1 to 20.
Please enter a number: 17
Input was valid! User entered 17.

In order to change the permissible range, you can change the lines

#define MIN_INPUT_NUMBER 1
#define MAX_INPUT_NUMBER 20

in the program.

答案3

得分: 0

这是您提供的代码的翻译部分:

检查是否为 'q' 的代码如下:

char *readLine(int nr) {
   int ch, i=0;
   char *string;
   string = malloc(nr);

   while((ch = getchar()) != '\n') {
       if(i<nr && isdigit(ch)!=0) {
          string[i++]=ch;
       }       
       else if (ch=='q' && i==0 && getchar()=='\n')
       {
        string[i++]=ch;
        return string;
       }                      
       else {
          string=NULL;
          return string;
       }
   }
   string[i]='
检查是否为 'q' 的代码如下:

char *readLine(int nr) {
   int ch, i=0;
   char *string;
   string = malloc(nr);

   while((ch = getchar()) != '\n') {
       if(i<nr && isdigit(ch)!=0) {
          string[i++]=ch;
       }       
       else if (ch=='q' && i==0 && getchar()=='\n')
       {
        string[i++]=ch;
        return string;
       }                      
       else {
          string=NULL;
          return string;
       }
   }
   string[i]='\0';
   return string;
} 


int main(void) {
   int number;

   printf("Enter a number or q: ");
   char *p=readLine(100);

   if(p==NULL) {
      printf("Invalid input!\n");
   }
   else if (p[0]=='q' && p[1]=='\0')   
   {
      printf("You entered q\n");
   }
   
   else {
      number=atoi(p);
      printf("Number as int is %d ", number);
   }
   free(p);

   return 0;
}
'
;
return string; } int main(void) { int number; printf("Enter a number or q: "); char *p=readLine(100); if(p==NULL) { printf("Invalid input!\n"); } else if (p[0]=='q' && p[1]=='
检查是否为 'q' 的代码如下:

char *readLine(int nr) {
   int ch, i=0;
   char *string;
   string = malloc(nr);

   while((ch = getchar()) != '\n') {
       if(i<nr && isdigit(ch)!=0) {
          string[i++]=ch;
       }       
       else if (ch=='q' && i==0 && getchar()=='\n')
       {
        string[i++]=ch;
        return string;
       }                      
       else {
          string=NULL;
          return string;
       }
   }
   string[i]='\0';
   return string;
} 


int main(void) {
   int number;

   printf("Enter a number or q: ");
   char *p=readLine(100);

   if(p==NULL) {
      printf("Invalid input!\n");
   }
   else if (p[0]=='q' && p[1]=='\0')   
   {
      printf("You entered q\n");
   }
   
   else {
      number=atoi(p);
      printf("Number as int is %d ", number);
   }
   free(p);

   return 0;
}
'
)
{ printf("You entered q\n"); } else { number=atoi(p); printf("Number as int is %d ", number); } free(p); return 0; }

希望这对您有所帮助。如果您有其他问题或需要进一步的翻译,请随时提出。

英文:

Checking also for 'q' your code would look like this:

char *readLine(int nr) {
   int ch, i=0;
   char *string;
   string = malloc(nr);

   while((ch = getchar()) != &#39;\n&#39;) {
       if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
          string[i++]=ch;
       }       
       else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
       {
        string[i++]=ch;
        return string;
       }                      
       else {
          string=NULL;
          return string;
       }
   }
   string[i]=&#39;
char *readLine(int nr) {
int ch, i=0;
char *string;
string = malloc(nr);
while((ch = getchar()) != &#39;\n&#39;) {
if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
string[i++]=ch;
}       
else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
{
string[i++]=ch;
return string;
}                      
else {
string=NULL;
return string;
}
}
string[i]=&#39;\0&#39;;
return string;
} 
int main(void) {
int number;
printf(&quot;Enter a number or q: &quot;);
char *p=readLine(100);
if(p==NULL) {
printf(&quot;Invalid input!\n&quot;);
}
else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;\0&#39;)   
{
printf(&quot;You entered q\n&quot;);
}
else {
number=atoi(p);
printf(&quot;Number as int is %d &quot;, number);
}
free(p);
return 0;
}
&#39;; return string; } int main(void) { int number; printf(&quot;Enter a number or q: &quot;); char *p=readLine(100); if(p==NULL) { printf(&quot;Invalid input!\n&quot;); } else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;
char *readLine(int nr) {
int ch, i=0;
char *string;
string = malloc(nr);
while((ch = getchar()) != &#39;\n&#39;) {
if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
string[i++]=ch;
}       
else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
{
string[i++]=ch;
return string;
}                      
else {
string=NULL;
return string;
}
}
string[i]=&#39;\0&#39;;
return string;
} 
int main(void) {
int number;
printf(&quot;Enter a number or q: &quot;);
char *p=readLine(100);
if(p==NULL) {
printf(&quot;Invalid input!\n&quot;);
}
else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;\0&#39;)   
{
printf(&quot;You entered q\n&quot;);
}
else {
number=atoi(p);
printf(&quot;Number as int is %d &quot;, number);
}
free(p);
return 0;
}
&#39;) { printf(&quot;You entered q\n&quot;); } else { number=atoi(p); printf(&quot;Number as int is %d &quot;, number); } free(p); return 0; }

huangapple
  • 本文由 发表于 2023年6月16日 01:11:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定