I got an error called "unable to convert string to char"
i used the statement
con = (char)(Console.Read());
Newbie here Please Help
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jun 7, 2013, 1:43 PM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
char choice;
char con ='y';
Console.WriteLine("What is the command keyword to exit a loop in C#?");
Console.WriteLine("a.quit");
Console.WriteLine("b.continue");
Console.WriteLine("c.break");
Console.WriteLine("d.exit");
while (con=='y')
{
Console.Write("\nEnter your choice:");
string input = Console.ReadLine();
if (input.Length != 1) continue;
choice = input[0];
if (choice == 'c')
{
Console.WriteLine("Congratulation!");
}
else if (choice == 'q' || choice == 'e')
{
Console.WriteLine("Exiting...!");
break;
}
else Console.WriteLine("Incorrect!");
Console.Write("Again? press y to continue:");
input = Console.ReadLine();
if(input.Length == 1)
{
con = input[0];
}
else break;
}
}
}
}
lendon medallePosted Jun 8, 2013, 10:06 PM
+1
lendon medallePosted Jun 7, 2013, 1:21 PM
I put already a Console.ReadLine(); at the end of the while loop but still the program exit without permission with me.
VulpesPosted Jun 6, 2013, 5:23 PM
Try this:
lendon medallePosted Jun 6, 2013, 3:02 PM
Sorry for copying it.
by the time i input an answer
the output will be like
Incorrect!
Again? press y to continue:
-> then it just exit with no prompt.
Congratulations!
Again? press y to continue:
-> then it just exit with no prompt.
using System;
Console.Write("Again? press y to continue:");using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
char choice;
char con='y';
Console.WriteLine("What is the command keyword to exit a loop in C#?");
Console.WriteLine("a.quit");
Console.WriteLine("b.continue");
Console.WriteLine("c.break");
Console.WriteLine("d.exit");
while (con=='y')
{
Console.Write("Enter your choice:");
choice = (char)(Console.Read());
if (choice == 'c')
{
Console.WriteLine("Congratulation!");
}
else if (choice == 'q' || choice == 'e') { Console.WriteLine("Exiting...!"); break; }
else Console.WriteLine("Incorrect!");
con = (char)(Console.Read());
}
}
}
}
VulpesPosted Jun 5, 2013, 2:17 PM
If you'd have used Console.ReadLine() instead of Console.Read() then you would have got the "unable to convert string to char" error because that method returns a string rather than an int.
So, I suspect the error is not occurring on that line but somewhere else?