2014-10-03 5 views
-6

나는 Lynda의 기본 교육 자습서를 따라하고 예제를 약간 변경하려고 C#을 배우려고합니다.'string'유형을 암시 적으로 'int'로 변환 할 수 없습니다. (CS0029)

Google에서 해결책을 찾을 수 없다는 오류가 발생합니다.

namespace l2 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 
      int arg; 
      arg = Console.ReadLine(); 
      int result1; 

      result1 = formula(arg); 
      Console.WriteLine("the result is {0}",result1); 
      Console.ReadKey(); 
     } 
     static int formula (int theVal){ 
      return (theVal * 2 + 15); 
     } 
     } 
    } 

내가 그 오류가 난 정말 왜 이해가 안 :

암시 'INT'(CS0029)

코드로 유형 '문자열을'변환 할 수 없습니다. 내 함수가 int를 얻고 있고, 콘솔에서 얻고 자하는 arg 또한 int이다. 컴파일러가 말하는 문자열은 어디에 있습니까? :)

+3

** [공식 MSDN 설명서] (http://msdn.microsoft.com/en-us/library/system.console.readline%28v=vs.110%29.aspx)를 참조하십시오 ** 'Console.ReadLine' **, 문자열 ** (int가 아닌) **을 반환합니다. –

+1

@marc_s, 맞습니다. 죄송합니다. 다시는 발생하지 않습니다. – SilenceIsGolden

답변

9

Console.ReadLine() 문자열을 반환합니다. 당신이 원하는 무엇

이 경우 올바른 해결책이 될 것입니다

arg = int.Parse(Console.ReadLine()); 
+1

확장하려면 ... 콘솔에 무엇이 있는지는 중요하지 않습니다. 항상 문자열로 읽습니다. 거기에서 변환해야합니다. – guildsbounty

+0

네 말이 맞지만 왜? arg = Console.ReadLine();의 arg는 기본적으로 문자열입니다. – SilenceIsGolden

+0

@ guildsbounty, 알겠습니다. 고맙습니다. – SilenceIsGolden

0

입니다.

string input; 
       input= Console.ReadLine(); 
       int numberArg; 
       while (!int.TryParse(input, out numberArg)) 
       { 
        Console.WriteLine(@"Wrong parameter. Type again."); 
        input= Console.ReadLine(); 
       } 

       var result1 = formula(numberArg); 
       Console.WriteLine("the result is {0}", result1); 
       Console.ReadKey(); 
0

int.TryParse을 사용하여 약간의 유효성 검사를 시도 할 수도 있습니다.

int id = 1; 
int.TryParse("Hello", out id); 
Console.WriteLine(id) 

출력 : 1

int id = 1; 
int.TryParse("40", out id); 
Console.WriteLine(id) 

출력 : 40

가 실제로 원래 값을 사용합니다 실패 할 경우 어떤, 값을 정수로 변환하려고 시도합니다 Console.ReadLine()string 유형을 반환합니다. 따라서 문제를 올바르게 해결하려면 다음을 수행하십시오.

int arguement = 0; 
while(!int.TryParse(Console.ReadLine(), out arguement) 
{ 
    Console.WriteLine(@"Error, invalid integer."); 
    Console.ReadLine(); 
} 

그래서 유효한 정수를 입력 할 때까지 루프에 트랩됩니다.

관련 문제