Cannot implicitly convert type string to int

前端 未结 4 1221
囚心锁ツ
囚心锁ツ 2020-12-21 16:34
    Console.WriteLine (\"Please enter some numbers\");
        int sum = 0;
        for(;;)
        {
            string input = Console.ReadLine ();
            if          


        
相关标签:
4条回答
  • 2020-12-21 17:16

    I would rewrite this entirely (Your original error was because you were trying to add a string to an int, and not the parsed input as an int)

    Console.WriteLine ("Please enter some numbers");
    int sum = 0;
    
    while (true)
    {
        int parsedInput = 0;
        string input = Console.ReadLine();
        if (!string.IsNullOrEmpty(input) && int.TryParse(input, out parsedInput))
        {
            sum += parsedInput;
            Console.WriteLine (sum);
        }
        else
        break;
    }
    
    0 讨论(0)
  • 2020-12-21 17:22

    to check if the input of the user is right i would prefer

    int userInput = 0;
    if( int.TryParse( input, out userInput ) == false )
    {
         break;
    }
    

    This is just an advise and not directly a solution to your problem. There are enough answers =)

    0 讨论(0)
  • 2020-12-21 17:24
    int inputParsed = int.Parse (input.ToString ());
                //int sumParsed = int.Parse (sum.ToString ());//no need
                sum = sum + inputParsed ; 
    
    0 讨论(0)
  • 2020-12-21 17:28
    sum = sum + input; //throws an error here
    

    should be:

    sum = sum + inputParsed ;
    

    You are using the original input instead of the parsed value. And you don't need sumParsed because you just keep the total sum in sum and you do no need to cast the int to a string and then parse it back to an integer.

    0 讨论(0)
提交回复
热议问题