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

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

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

问题

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

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. char *readLine(int nr) {
  5. int ch, i = 0;
  6. char *string;
  7. string = malloc(nr);
  8. while ((ch = getchar()) != '\n') {
  9. if (i < nr && isdigit(ch) != 0) {
  10. string[i++] = ch;
  11. } else if (i == 0 && ch == 'q') { // Check for 'q' as the first and only character
  12. string[i++] = ch;
  13. } else {
  14. free(string); // Free memory before returning NULL
  15. return NULL;
  16. }
  17. }
  18. string[i] = '
    #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <ctype.h>
  21. char *readLine(int nr) {
  22.     int ch, i = 0;
  23.     char *string;
  24.     string = malloc(nr);
  25.     while ((ch = getchar()) != '\n') {
  26.         if (i < nr && isdigit(ch) != 0) {
  27.             string[i++] = ch;
  28.         } else if (i == 0 && ch == 'q') { // Check for 'q' as the first and only character
  29.             string[i++] = ch;
  30.         } else {
  31.             free(string); // Free memory before returning NULL
  32.             return NULL;
  33.         }
  34.     }
  35.     string[i] = '\0';
  36.     return string;
  37. }
  38. int main(void) {
  39.     int number;
  40.     printf("Enter number: ");
  41.     char *p = readLine(100);
  42.     if (p == NULL) {
  43.         printf("Invalid input!\n");
  44.     } else {
  45.         number = atoi(p);
  46.         printf("Number as int is %d ", number);
  47.     }
  48.     free(p);
  49.     return 0;
  50. }
  51. ';
  52. return string;
  53. }
  54. int main(void) {
  55. int number;
  56. printf("Enter number: ");
  57. char *p = readLine(100);
  58. if (p == NULL) {
  59. printf("Invalid input!\n");
  60. } else {
  61. number = atoi(p);
  62. printf("Number as int is %d ", number);
  63. }
  64. free(p);
  65. return 0;
  66. }

我在代码中添加了一个检查,以确保字母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):

  1. char *readLine(int nr) {
  2. int ch, i=0;
  3. char *string;
  4. string = malloc(nr);
  5. while((ch = getchar()) != &#39;\n&#39;) {
  6. if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
  7. string[i++]=ch;
  8. }
  9. else {
  10. string=NULL;
  11. return string;
  12. }
  13. }
  14. string[i]=&#39;
    char *readLine(int nr) {
  15. int ch, i=0;
  16. char *string;
  17. string = malloc(nr);
  18. while((ch = getchar()) != &#39;\n&#39;) {
  19. if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
  20. string[i++]=ch;
  21. }
  22. else {
  23. string=NULL;
  24. return string;
  25. }
  26. }
  27. string[i]=&#39;\0&#39;;
  28. return string;
  29. } 
  30. int main(void) {
  31. int number;
  32. printf(&quot;Enter number: &quot;);
  33. char *p=readLine(100);
  34. if(p==NULL) {
  35. printf(&quot;Invalid input!\n&quot;);
  36. }
  37. else {
  38. number=atoi(p);
  39. printf(&quot;Number as int is %d &quot;, number);
  40. }
  41. free(p);
  42. return 0;
  43. }
  44. &#39;;
  45. return string;
  46. }
  47. int main(void) {
  48. int number;
  49. printf(&quot;Enter number: &quot;);
  50. char *p=readLine(100);
  51. if(p==NULL) {
  52. printf(&quot;Invalid input!\n&quot;);
  53. }
  54. else {
  55. number=atoi(p);
  56. printf(&quot;Number as int is %d &quot;, number);
  57. }
  58. free(p);
  59. return 0;
  60. }

答案1

得分: 2

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

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

  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. char *readLine(int nr) {
  6. int ch, i = 0, q_entered = 0;
  7. char *string;
  8. string = malloc(nr);
  9. while ((ch = getchar()) != '\n') {
  10. if (i < nr && !q_entered && isdigit(ch) != 0) {
  11. string[i++] = ch;
  12. } else if (i == 0 && ch == 'q') {
  13. string[i++] = ch;
  14. q_entered = 1;
  15. } else {
  16. free(string);
  17. return NULL;
  18. }
  19. }
  20. string[i] = '
    #include <stdio.h>
  21. #include <ctype.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. char *readLine(int nr) {
  25.     int ch, i = 0, q_entered = 0;
  26.     char *string;
  27.     string = malloc(nr);
  28.     while ((ch = getchar()) != '\n') {
  29.         if (i < nr && !q_entered && isdigit(ch) != 0) {
  30.             string[i++] = ch;
  31.         } else if (i == 0 && ch == 'q') {
  32.             string[i++] = ch;
  33.             q_entered = 1;
  34.         } else {
  35.             free(string);
  36.             return NULL;
  37.         }
  38.     }
  39.     string[i] = '\0';
  40.     return string;
  41. }
  42. int main(void) {
  43.     int number;
  44.     printf("Enter number: ");
  45.     char *p = readLine(100);
  46.     if (p == NULL) {
  47.         printf("Invalid input!\n");
  48.     } else if (strcmp(p, "q") == 0) {
  49.         printf("Quitting\n");
  50.     } else {
  51.         number = atoi(p);
  52.         printf("Number as int is %d\n", number);
  53.     }
  54.     free(p);
  55.     return 0;
  56. }
  57. ';
  58. return string;
  59. }
  60. int main(void) {
  61. int number;
  62. printf("Enter number: ");
  63. char *p = readLine(100);
  64. if (p == NULL) {
  65. printf("Invalid input!\n");
  66. } else if (strcmp(p, "q") == 0) {
  67. printf("Quitting\n");
  68. } else {
  69. number = atoi(p);
  70. printf("Number as int is %d\n", number);
  71. }
  72. free(p);
  73. return 0;
  74. }

尽管如此,更好的设计通常是将输入代码与解析输入的代码分离开来。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().

  1. #include &lt;stdio.h&gt;
  2. #include &lt;ctype.h&gt;
  3. #include &lt;stdlib.h&gt;
  4. #include &lt;string.h&gt;
  5. char *readLine(int nr) {
  6. int ch, i=0, q_entered = 0;
  7. char *string;
  8. string = malloc(nr);
  9. while((ch = getchar()) != &#39;\n&#39;) {
  10. if(i&lt;nr &amp;&amp; !q_entered &amp;&amp; isdigit(ch)!=0) {
  11. string[i++]=ch;
  12. } else if (i == 0 &amp;&amp; ch == &#39;q&#39;) {
  13. string[i++] = ch;
  14. q_entered = 1;
  15. } else {
  16. free(string);
  17. return NULL;
  18. }
  19. }
  20. string[i]=&#39;
    #include &lt;stdio.h&gt;
  21. #include &lt;ctype.h&gt;
  22. #include &lt;stdlib.h&gt;
  23. #include &lt;string.h&gt;
  24. char *readLine(int nr) {
  25. int ch, i=0, q_entered = 0;
  26. char *string;
  27. string = malloc(nr);
  28. while((ch = getchar()) != &#39;\n&#39;) {
  29. if(i&lt;nr &amp;&amp; !q_entered &amp;&amp; isdigit(ch)!=0) {
  30. string[i++]=ch;
  31. } else if (i == 0 &amp;&amp; ch == &#39;q&#39;) {
  32. string[i++] = ch;
  33. q_entered = 1;
  34. } else {
  35. free(string);
  36. return NULL;
  37. }
  38. }
  39. string[i]=&#39;\0&#39;;
  40. return string;
  41. }
  42. int main(void) {
  43. int number;
  44. printf(&quot;Enter number: &quot;);
  45. char *p=readLine(100);
  46. if(p==NULL) {
  47. printf(&quot;Invalid input!\n&quot;);
  48. } else if (strcmp(p, &quot;q&quot;) == 0) {
  49. printf(&quot;Quitting\n&quot;);
  50. } else {
  51. number=atoi(p);
  52. printf(&quot;Number as int is %d\n&quot;, number);
  53. }
  54. free(p);
  55. return 0;
  56. }
  57. &#39;;
  58. return string;
  59. }
  60. int main(void) {
  61. int number;
  62. printf(&quot;Enter number: &quot;);
  63. char *p=readLine(100);
  64. if(p==NULL) {
  65. printf(&quot;Invalid input!\n&quot;);
  66. } else if (strcmp(p, &quot;q&quot;) == 0) {
  67. printf(&quot;Quitting\n&quot;);
  68. } else {
  69. number=atoi(p);
  70. printf(&quot;Number as int is %d\n&quot;, number);
  71. }
  72. free(p);
  73. return 0;
  74. }

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 的范围内。

以下是一个示例:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <errno.h>
  6. #define MIN_INPUT_NUMBER 1
  7. #define MAX_INPUT_NUMBER 20
  8. void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
  9. int main( void )
  10. {
  11. // ... (同上提供的代码)
  12. }
  13. // get_line_from_user 函数的翻译部分见下方

此程序具有以下行为:

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

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

  1. #define MIN_INPUT_NUMBER 1
  2. #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:

  1. #include &lt;stdio.h&gt;
  2. #include &lt;stdlib.h&gt;
  3. #include &lt;string.h&gt;
  4. #include &lt;ctype.h&gt;
  5. #include &lt;errno.h&gt;
  6. #define MIN_INPUT_NUMBER 1
  7. #define MAX_INPUT_NUMBER 20
  8. void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
  9. int main( void )
  10. {
  11. char line[200], *p;
  12. long num;
  13. //read exactly one line of input from the user
  14. get_line_from_user(
  15. &quot;Please enter a number: &quot;,
  16. line, sizeof line
  17. );
  18. //determine whether the user entered `&quot;q&quot;` as input
  19. if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;
    #include &lt;stdio.h&gt;
  20. #include &lt;stdlib.h&gt;
  21. #include &lt;string.h&gt;
  22. #include &lt;ctype.h&gt;
  23. #include &lt;errno.h&gt;
  24. #define MIN_INPUT_NUMBER 1
  25. #define MAX_INPUT_NUMBER 20
  26. void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
  27. int main( void )
  28. {
  29. char line[200], *p;
  30. long num;
  31. //read exactly one line of input from the user
  32. get_line_from_user(
  33. &quot;Please enter a number: &quot;,
  34. line, sizeof line
  35. );
  36. //determine whether the user entered `&quot;q&quot;` as input
  37. if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
  38. {
  39. printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
  40. exit( EXIT_SUCCESS );
  41. }
  42. //attempt to convert input to a number
  43. errno = 0;
  44. num = strtol( line, &amp;p, 10 );
  45. //verify that at least one character was converted
  46. if ( p == line )
  47. {
  48. printf( &quot;Error: Unable to convert input to integer!\n&quot; );
  49. exit( EXIT_FAILURE );
  50. }
  51. //verify that input is not too small or too large to be
  52. //representable as a `long int`
  53. if ( errno == ERANGE )
  54. {
  55. printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
  56. exit( EXIT_FAILURE );
  57. }
  58. //verify that either all characters were converted or that all
  59. //remaining characters are whitespace characters, so that input
  60. //such as &quot;242q42&quot; gets rejected
  61. for ( ; *p != &#39;\0&#39;; p++ )
  62. {
  63. if ( !isspace( (unsigned char)*p ) )
  64. {
  65. printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
  66. exit( EXIT_FAILURE );
  67. }
  68. }
  69. //verify that the converted integer is in the desired range
  70. if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
  71. {
  72. printf(
  73. &quot;Error: Input must be in the range %d to %d.\n&quot;,
  74. MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
  75. );
  76. exit( EXIT_FAILURE );
  77. }
  78. //everything went ok, so print the result
  79. printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
  80. return EXIT_SUCCESS;
  81. }
  82. //This function will read exactly one line of input from the
  83. //user. It will remove the newline character, if it exists. If
  84. //the line is too long to fit in the buffer, then the function
  85. //will automatically reprompt the user for input. On failure,
  86. //the function will never return, but will print an error
  87. //message and call &quot;exit&quot; instead.
  88. void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
  89. {
  90. for (;;) //infinite loop, equivalent to while(1)
  91. {
  92. char *p;
  93. //prompt user for input
  94. fputs( prompt, stdout );
  95. //attempt to read one line of input
  96. if ( fgets( buffer, buffer_size, stdin ) == NULL )
  97. {
  98. printf( &quot;Error reading from input!\n&quot; );
  99. exit( EXIT_FAILURE );
  100. }
  101. //attempt to find newline character
  102. p = strchr( buffer, &#39;\n&#39; );
  103. //make sure that entire line was read in (i.e. that
  104. //the buffer was not too small to store the entire line)
  105. if ( p == NULL )
  106. {
  107. int c;
  108. //a missing newline character is ok if the next
  109. //character is a newline character or if we have
  110. //reached end-of-file (for example if the input is
  111. //being piped from a file or if the user enters
  112. //end-of-file in the terminal itself)
  113. if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
  114. {
  115. if ( c == EOF )
  116. {
  117. printf( &quot;Error reading from input!\n&quot; );
  118. exit( EXIT_FAILURE );
  119. }
  120. printf( &quot;Input was too long to fit in buffer!\n&quot; );
  121. //discard remainder of line
  122. do
  123. {
  124. c = getchar();
  125. if ( c == EOF )
  126. {
  127. //this error message will be printed if either
  128. //a stream error or an unexpected end-of-file
  129. //is encountered
  130. printf( &quot;Error reading from input!\n&quot; );
  131. exit( EXIT_FAILURE );
  132. }
  133. } while ( c != &#39;\n&#39; );
  134. //reprompt user for input by restarting loop
  135. continue;
  136. }
  137. }
  138. else
  139. {
  140. //remove newline character by overwriting it with
  141. //null character
  142. *p = &#39;\0&#39;;
  143. }
  144. //input was ok, so break out of loop
  145. break;
  146. }
  147. }
  148. &#39; )
  149. {
  150. printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
  151. exit( EXIT_SUCCESS );
  152. }
  153. //attempt to convert input to a number
  154. errno = 0;
  155. num = strtol( line, &amp;p, 10 );
  156. //verify that at least one character was converted
  157. if ( p == line )
  158. {
  159. printf( &quot;Error: Unable to convert input to integer!\n&quot; );
  160. exit( EXIT_FAILURE );
  161. }
  162. //verify that input is not too small or too large to be
  163. //representable as a `long int`
  164. if ( errno == ERANGE )
  165. {
  166. printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
  167. exit( EXIT_FAILURE );
  168. }
  169. //verify that either all characters were converted or that all
  170. //remaining characters are whitespace characters, so that input
  171. //such as &quot;242q42&quot; gets rejected
  172. for ( ; *p != &#39;
    #include &lt;stdio.h&gt;
  173. #include &lt;stdlib.h&gt;
  174. #include &lt;string.h&gt;
  175. #include &lt;ctype.h&gt;
  176. #include &lt;errno.h&gt;
  177. #define MIN_INPUT_NUMBER 1
  178. #define MAX_INPUT_NUMBER 20
  179. void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
  180. int main( void )
  181. {
  182. char line[200], *p;
  183. long num;
  184. //read exactly one line of input from the user
  185. get_line_from_user(
  186. &quot;Please enter a number: &quot;,
  187. line, sizeof line
  188. );
  189. //determine whether the user entered `&quot;q&quot;` as input
  190. if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
  191. {
  192. printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
  193. exit( EXIT_SUCCESS );
  194. }
  195. //attempt to convert input to a number
  196. errno = 0;
  197. num = strtol( line, &amp;p, 10 );
  198. //verify that at least one character was converted
  199. if ( p == line )
  200. {
  201. printf( &quot;Error: Unable to convert input to integer!\n&quot; );
  202. exit( EXIT_FAILURE );
  203. }
  204. //verify that input is not too small or too large to be
  205. //representable as a `long int`
  206. if ( errno == ERANGE )
  207. {
  208. printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
  209. exit( EXIT_FAILURE );
  210. }
  211. //verify that either all characters were converted or that all
  212. //remaining characters are whitespace characters, so that input
  213. //such as &quot;242q42&quot; gets rejected
  214. for ( ; *p != &#39;\0&#39;; p++ )
  215. {
  216. if ( !isspace( (unsigned char)*p ) )
  217. {
  218. printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
  219. exit( EXIT_FAILURE );
  220. }
  221. }
  222. //verify that the converted integer is in the desired range
  223. if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
  224. {
  225. printf(
  226. &quot;Error: Input must be in the range %d to %d.\n&quot;,
  227. MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
  228. );
  229. exit( EXIT_FAILURE );
  230. }
  231. //everything went ok, so print the result
  232. printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
  233. return EXIT_SUCCESS;
  234. }
  235. //This function will read exactly one line of input from the
  236. //user. It will remove the newline character, if it exists. If
  237. //the line is too long to fit in the buffer, then the function
  238. //will automatically reprompt the user for input. On failure,
  239. //the function will never return, but will print an error
  240. //message and call &quot;exit&quot; instead.
  241. void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
  242. {
  243. for (;;) //infinite loop, equivalent to while(1)
  244. {
  245. char *p;
  246. //prompt user for input
  247. fputs( prompt, stdout );
  248. //attempt to read one line of input
  249. if ( fgets( buffer, buffer_size, stdin ) == NULL )
  250. {
  251. printf( &quot;Error reading from input!\n&quot; );
  252. exit( EXIT_FAILURE );
  253. }
  254. //attempt to find newline character
  255. p = strchr( buffer, &#39;\n&#39; );
  256. //make sure that entire line was read in (i.e. that
  257. //the buffer was not too small to store the entire line)
  258. if ( p == NULL )
  259. {
  260. int c;
  261. //a missing newline character is ok if the next
  262. //character is a newline character or if we have
  263. //reached end-of-file (for example if the input is
  264. //being piped from a file or if the user enters
  265. //end-of-file in the terminal itself)
  266. if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
  267. {
  268. if ( c == EOF )
  269. {
  270. printf( &quot;Error reading from input!\n&quot; );
  271. exit( EXIT_FAILURE );
  272. }
  273. printf( &quot;Input was too long to fit in buffer!\n&quot; );
  274. //discard remainder of line
  275. do
  276. {
  277. c = getchar();
  278. if ( c == EOF )
  279. {
  280. //this error message will be printed if either
  281. //a stream error or an unexpected end-of-file
  282. //is encountered
  283. printf( &quot;Error reading from input!\n&quot; );
  284. exit( EXIT_FAILURE );
  285. }
  286. } while ( c != &#39;\n&#39; );
  287. //reprompt user for input by restarting loop
  288. continue;
  289. }
  290. }
  291. else
  292. {
  293. //remove newline character by overwriting it with
  294. //null character
  295. *p = &#39;\0&#39;;
  296. }
  297. //input was ok, so break out of loop
  298. break;
  299. }
  300. }
  301. &#39;; p++ )
  302. {
  303. if ( !isspace( (unsigned char)*p ) )
  304. {
  305. printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
  306. exit( EXIT_FAILURE );
  307. }
  308. }
  309. //verify that the converted integer is in the desired range
  310. if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
  311. {
  312. printf(
  313. &quot;Error: Input must be in the range %d to %d.\n&quot;,
  314. MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
  315. );
  316. exit( EXIT_FAILURE );
  317. }
  318. //everything went ok, so print the result
  319. printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
  320. return EXIT_SUCCESS;
  321. }
  322. //This function will read exactly one line of input from the
  323. //user. It will remove the newline character, if it exists. If
  324. //the line is too long to fit in the buffer, then the function
  325. //will automatically reprompt the user for input. On failure,
  326. //the function will never return, but will print an error
  327. //message and call &quot;exit&quot; instead.
  328. void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
  329. {
  330. for (;;) //infinite loop, equivalent to while(1)
  331. {
  332. char *p;
  333. //prompt user for input
  334. fputs( prompt, stdout );
  335. //attempt to read one line of input
  336. if ( fgets( buffer, buffer_size, stdin ) == NULL )
  337. {
  338. printf( &quot;Error reading from input!\n&quot; );
  339. exit( EXIT_FAILURE );
  340. }
  341. //attempt to find newline character
  342. p = strchr( buffer, &#39;\n&#39; );
  343. //make sure that entire line was read in (i.e. that
  344. //the buffer was not too small to store the entire line)
  345. if ( p == NULL )
  346. {
  347. int c;
  348. //a missing newline character is ok if the next
  349. //character is a newline character or if we have
  350. //reached end-of-file (for example if the input is
  351. //being piped from a file or if the user enters
  352. //end-of-file in the terminal itself)
  353. if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
  354. {
  355. if ( c == EOF )
  356. {
  357. printf( &quot;Error reading from input!\n&quot; );
  358. exit( EXIT_FAILURE );
  359. }
  360. printf( &quot;Input was too long to fit in buffer!\n&quot; );
  361. //discard remainder of line
  362. do
  363. {
  364. c = getchar();
  365. if ( c == EOF )
  366. {
  367. //this error message will be printed if either
  368. //a stream error or an unexpected end-of-file
  369. //is encountered
  370. printf( &quot;Error reading from input!\n&quot; );
  371. exit( EXIT_FAILURE );
  372. }
  373. } while ( c != &#39;\n&#39; );
  374. //reprompt user for input by restarting loop
  375. continue;
  376. }
  377. }
  378. else
  379. {
  380. //remove newline character by overwriting it with
  381. //null character
  382. *p = &#39;
    #include &lt;stdio.h&gt;
  383. #include &lt;stdlib.h&gt;
  384. #include &lt;string.h&gt;
  385. #include &lt;ctype.h&gt;
  386. #include &lt;errno.h&gt;
  387. #define MIN_INPUT_NUMBER 1
  388. #define MAX_INPUT_NUMBER 20
  389. void get_line_from_user( const char prompt[], char buffer[], int buffer_size );
  390. int main( void )
  391. {
  392. char line[200], *p;
  393. long num;
  394. //read exactly one line of input from the user
  395. get_line_from_user(
  396. &quot;Please enter a number: &quot;,
  397. line, sizeof line
  398. );
  399. //determine whether the user entered `&quot;q&quot;` as input
  400. if ( line[0] == &#39;q&#39; &amp;&amp; line[1] == &#39;\0&#39; )
  401. {
  402. printf( &quot;Input is valid, user entered \&quot;q\&quot;.\n&quot; );
  403. exit( EXIT_SUCCESS );
  404. }
  405. //attempt to convert input to a number
  406. errno = 0;
  407. num = strtol( line, &amp;p, 10 );
  408. //verify that at least one character was converted
  409. if ( p == line )
  410. {
  411. printf( &quot;Error: Unable to convert input to integer!\n&quot; );
  412. exit( EXIT_FAILURE );
  413. }
  414. //verify that input is not too small or too large to be
  415. //representable as a `long int`
  416. if ( errno == ERANGE )
  417. {
  418. printf( &quot;Error: Input is outside the range of a long int!\n&quot; );
  419. exit( EXIT_FAILURE );
  420. }
  421. //verify that either all characters were converted or that all
  422. //remaining characters are whitespace characters, so that input
  423. //such as &quot;242q42&quot; gets rejected
  424. for ( ; *p != &#39;\0&#39;; p++ )
  425. {
  426. if ( !isspace( (unsigned char)*p ) )
  427. {
  428. printf( &quot;Error: Not all non-whitespace characters were converted!\n&quot; );
  429. exit( EXIT_FAILURE );
  430. }
  431. }
  432. //verify that the converted integer is in the desired range
  433. if ( num &lt; MIN_INPUT_NUMBER || num &gt; MAX_INPUT_NUMBER )
  434. {
  435. printf(
  436. &quot;Error: Input must be in the range %d to %d.\n&quot;,
  437. MIN_INPUT_NUMBER, MAX_INPUT_NUMBER
  438. );
  439. exit( EXIT_FAILURE );
  440. }
  441. //everything went ok, so print the result
  442. printf( &quot;Input was valid! User entered %ld.\n&quot;, num );
  443. return EXIT_SUCCESS;
  444. }
  445. //This function will read exactly one line of input from the
  446. //user. It will remove the newline character, if it exists. If
  447. //the line is too long to fit in the buffer, then the function
  448. //will automatically reprompt the user for input. On failure,
  449. //the function will never return, but will print an error
  450. //message and call &quot;exit&quot; instead.
  451. void get_line_from_user( const char prompt[], char buffer[], int buffer_size )
  452. {
  453. for (;;) //infinite loop, equivalent to while(1)
  454. {
  455. char *p;
  456. //prompt user for input
  457. fputs( prompt, stdout );
  458. //attempt to read one line of input
  459. if ( fgets( buffer, buffer_size, stdin ) == NULL )
  460. {
  461. printf( &quot;Error reading from input!\n&quot; );
  462. exit( EXIT_FAILURE );
  463. }
  464. //attempt to find newline character
  465. p = strchr( buffer, &#39;\n&#39; );
  466. //make sure that entire line was read in (i.e. that
  467. //the buffer was not too small to store the entire line)
  468. if ( p == NULL )
  469. {
  470. int c;
  471. //a missing newline character is ok if the next
  472. //character is a newline character or if we have
  473. //reached end-of-file (for example if the input is
  474. //being piped from a file or if the user enters
  475. //end-of-file in the terminal itself)
  476. if ( (c=getchar()) != &#39;\n&#39; &amp;&amp; !feof(stdin) )
  477. {
  478. if ( c == EOF )
  479. {
  480. printf( &quot;Error reading from input!\n&quot; );
  481. exit( EXIT_FAILURE );
  482. }
  483. printf( &quot;Input was too long to fit in buffer!\n&quot; );
  484. //discard remainder of line
  485. do
  486. {
  487. c = getchar();
  488. if ( c == EOF )
  489. {
  490. //this error message will be printed if either
  491. //a stream error or an unexpected end-of-file
  492. //is encountered
  493. printf( &quot;Error reading from input!\n&quot; );
  494. exit( EXIT_FAILURE );
  495. }
  496. } while ( c != &#39;\n&#39; );
  497. //reprompt user for input by restarting loop
  498. continue;
  499. }
  500. }
  501. else
  502. {
  503. //remove newline character by overwriting it with
  504. //null character
  505. *p = &#39;\0&#39;;
  506. }
  507. //input was ok, so break out of loop
  508. break;
  509. }
  510. }
  511. &#39;;
  512. }
  513. //input was ok, so break out of loop
  514. break;
  515. }
  516. }

This program has the following behavior:

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

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

  1. #define MIN_INPUT_NUMBER 1
  2. #define MAX_INPUT_NUMBER 20

in the program.

答案3

得分: 0

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

  1. 检查是否为 'q' 的代码如下:
  2. char *readLine(int nr) {
  3. int ch, i=0;
  4. char *string;
  5. string = malloc(nr);
  6. while((ch = getchar()) != '\n') {
  7. if(i<nr && isdigit(ch)!=0) {
  8. string[i++]=ch;
  9. }
  10. else if (ch=='q' && i==0 && getchar()=='\n')
  11. {
  12. string[i++]=ch;
  13. return string;
  14. }
  15. else {
  16. string=NULL;
  17. return string;
  18. }
  19. }
  20. string[i]='
    检查是否为 'q' 的代码如下:
  21. char *readLine(int nr) {
  22.    int ch, i=0;
  23.    char *string;
  24.    string = malloc(nr);
  25.    while((ch = getchar()) != '\n') {
  26.        if(i<nr && isdigit(ch)!=0) {
  27.           string[i++]=ch;
  28.        }       
  29.        else if (ch=='q' && i==0 && getchar()=='\n')
  30.        {
  31.         string[i++]=ch;
  32.         return string;
  33.        }                      
  34.        else {
  35.           string=NULL;
  36.           return string;
  37.        }
  38.    }
  39.    string[i]='\0';
  40.    return string;
  41. } 
  42. int main(void) {
  43.    int number;
  44.    printf("Enter a number or q: ");
  45.    char *p=readLine(100);
  46.    if(p==NULL) {
  47.       printf("Invalid input!\n");
  48.    }
  49.    else if (p[0]=='q' && p[1]=='\0')   
  50.    {
  51.       printf("You entered q\n");
  52.    }
  53.    
  54.    else {
  55.       number=atoi(p);
  56.       printf("Number as int is %d ", number);
  57.    }
  58.    free(p);
  59.    return 0;
  60. }
  61. ';
  62. return string;
  63. }
  64. int main(void) {
  65. int number;
  66. printf("Enter a number or q: ");
  67. char *p=readLine(100);
  68. if(p==NULL) {
  69. printf("Invalid input!\n");
  70. }
  71. else if (p[0]=='q' && p[1]=='
    检查是否为 'q' 的代码如下:
  72. char *readLine(int nr) {
  73.    int ch, i=0;
  74.    char *string;
  75.    string = malloc(nr);
  76.    while((ch = getchar()) != '\n') {
  77.        if(i<nr && isdigit(ch)!=0) {
  78.           string[i++]=ch;
  79.        }       
  80.        else if (ch=='q' && i==0 && getchar()=='\n')
  81.        {
  82.         string[i++]=ch;
  83.         return string;
  84.        }                      
  85.        else {
  86.           string=NULL;
  87.           return string;
  88.        }
  89.    }
  90.    string[i]='\0';
  91.    return string;
  92. } 
  93. int main(void) {
  94.    int number;
  95.    printf("Enter a number or q: ");
  96.    char *p=readLine(100);
  97.    if(p==NULL) {
  98.       printf("Invalid input!\n");
  99.    }
  100.    else if (p[0]=='q' && p[1]=='\0')   
  101.    {
  102.       printf("You entered q\n");
  103.    }
  104.    
  105.    else {
  106.       number=atoi(p);
  107.       printf("Number as int is %d ", number);
  108.    }
  109.    free(p);
  110.    return 0;
  111. }
  112. ')
  113. {
  114. printf("You entered q\n");
  115. }
  116. else {
  117. number=atoi(p);
  118. printf("Number as int is %d ", number);
  119. }
  120. free(p);
  121. return 0;
  122. }

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

英文:

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

  1. char *readLine(int nr) {
  2. int ch, i=0;
  3. char *string;
  4. string = malloc(nr);
  5. while((ch = getchar()) != &#39;\n&#39;) {
  6. if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
  7. string[i++]=ch;
  8. }
  9. else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
  10. {
  11. string[i++]=ch;
  12. return string;
  13. }
  14. else {
  15. string=NULL;
  16. return string;
  17. }
  18. }
  19. string[i]=&#39;
    char *readLine(int nr) {
  20. int ch, i=0;
  21. char *string;
  22. string = malloc(nr);
  23. while((ch = getchar()) != &#39;\n&#39;) {
  24. if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
  25. string[i++]=ch;
  26. }       
  27. else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
  28. {
  29. string[i++]=ch;
  30. return string;
  31. }                      
  32. else {
  33. string=NULL;
  34. return string;
  35. }
  36. }
  37. string[i]=&#39;\0&#39;;
  38. return string;
  39. } 
  40. int main(void) {
  41. int number;
  42. printf(&quot;Enter a number or q: &quot;);
  43. char *p=readLine(100);
  44. if(p==NULL) {
  45. printf(&quot;Invalid input!\n&quot;);
  46. }
  47. else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;\0&#39;)   
  48. {
  49. printf(&quot;You entered q\n&quot;);
  50. }
  51. else {
  52. number=atoi(p);
  53. printf(&quot;Number as int is %d &quot;, number);
  54. }
  55. free(p);
  56. return 0;
  57. }
  58. &#39;;
  59. return string;
  60. }
  61. int main(void) {
  62. int number;
  63. printf(&quot;Enter a number or q: &quot;);
  64. char *p=readLine(100);
  65. if(p==NULL) {
  66. printf(&quot;Invalid input!\n&quot;);
  67. }
  68. else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;
    char *readLine(int nr) {
  69. int ch, i=0;
  70. char *string;
  71. string = malloc(nr);
  72. while((ch = getchar()) != &#39;\n&#39;) {
  73. if(i&lt;nr &amp;&amp; isdigit(ch)!=0) {
  74. string[i++]=ch;
  75. }       
  76. else if (ch==&#39;q&#39; &amp;&amp; i==0 &amp;&amp; getchar()==&#39;\n&#39;)
  77. {
  78. string[i++]=ch;
  79. return string;
  80. }                      
  81. else {
  82. string=NULL;
  83. return string;
  84. }
  85. }
  86. string[i]=&#39;\0&#39;;
  87. return string;
  88. } 
  89. int main(void) {
  90. int number;
  91. printf(&quot;Enter a number or q: &quot;);
  92. char *p=readLine(100);
  93. if(p==NULL) {
  94. printf(&quot;Invalid input!\n&quot;);
  95. }
  96. else if (p[0]==&#39;q&#39; &amp;&amp; p[1]==&#39;\0&#39;)   
  97. {
  98. printf(&quot;You entered q\n&quot;);
  99. }
  100. else {
  101. number=atoi(p);
  102. printf(&quot;Number as int is %d &quot;, number);
  103. }
  104. free(p);
  105. return 0;
  106. }
  107. &#39;)
  108. {
  109. printf(&quot;You entered q\n&quot;);
  110. }
  111. else {
  112. number=atoi(p);
  113. printf(&quot;Number as int is %d &quot;, number);
  114. }
  115. free(p);
  116. return 0;
  117. }

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:

确定