Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        4年前关闭。
                                                                                            
                
        
我必须编写一个将用户输入(字符串)转换为Integer的程序。同时应检查用户输入的内容是否确实是数字。
还有一切,只需一种方法。

并且不允许使用库函数。

我不知道该怎么做。一开始我所得到的只是这个可悲的结构

#include <stdio.h>

void main()
{
  char input[100];
  int i;
  int sum = 0;
  printf("Type a String which will be converted to an Integer: ");
  scanf("%c, &input");

  for (i = 0; i < 100; i++)
   {

   }
}


感谢您的帮助,谢谢

最佳答案

取最高位数并加到数字上,再乘以10,再加上下一位。等等:

#include <stdio.h> // scanf, printf

void main()
{
    char input[100];
    printf("Type a String which will be converted to an Integer: ");
    scanf("%s", input);

    int number = 0;
    int neg = input[0] == '-';
    int i = neg ? 1 : 0;
    while ( input[i] >= '0' && input[i] <= '9' )
    {
      number *= 10;             // multiply number by 10
      number += input[i] - '0'; // convet ASCII '0'..'9' to digit 0..9 and add it to number
      i ++;                     // step one digit forward
    }
    if ( neg )
       number *= -1;

    printf( "string %s -> number %d", input, number );
}

input[i] - '0'起作用,因为ASCII字符'0'..'9'具有从48到57的升序ASCII码。

10-08 03:03