Hanya Idrees
Hanya Idrees

Reputation: 451

Conversion from String to Char in visual c++

I am taking input from user in visual c++ through the following code

Console::WriteLine("Select the Cache Size.\n a. 1 Kb \n b. 2 Kb \n c. 4 Kb \n d. 8 Kb\n");
    String^ CACHE_SIZEoption = Console::ReadLine();
    Char wh= Char(CACHE_SIZEoption);

    switch(wh)
    {case 'a':
    break;

    case 'b':
    break;

    case 'c':
     break;

    case 'd':
    break;
    }

In this the conversion from String to Char is giving errors..

 error C2440: '<function-style-cast>' : cannot convert from 'System::String ^' to 'wchar_t'

Upvotes: 0

Views: 305

Answers (2)

TobiMcNamobi
TobiMcNamobi

Reputation: 4813

I would try

Char wh= CACHE_SIZEoption[0];

or

Char wh= CACHE_SIZEoption->ToChar();

Found here: http://msdn.microsoft.com/en-us/library/bb335877%28v=vs.110%29.aspx

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

It's unrealistic to expect to be able to convert a string into a character. A string can contain 0, 1 or more characters. Which character do you want?

If you want the first character, use CACHE_SIZEoption[0], after having checked that the string is not empty.

In your case you probably want to add a check that the string's length is exactly 1 because otherwise that means the user's input is invalid. Check CACHE_SIZEoption->Length.

Upvotes: 2

Related Questions