Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

vb.net - Comparisons in C VS VB

Here is the C code:

do
{
    printf("
Over eighteen (Y/N): ");
    scanf("%c", over18);

    if(over18 != "Y" || over18 != "N")
    {
        printf("
Invalid input");
    }

}  while(over18 != "Y" && over18 != "N");

Hey, I am new to C and I am trying to sort-off translate my old VB code from when I was learning that into C. I have attempted to do that for this part of a program, but that gives the error "warning: comparison between pointer and integer" for all my comparisons using "!=".
Here is the VB code:

    Do
        Console.WriteLine("Are you over eighteen (Y/N)?")
        over18 = Console.ReadLine()

        If over18 <> "Y" And over18 <> "N" Then
            Console.WriteLine("That is not a valid answer")
        End If

    Loop Until over18 = "Y" Or over18 = "N"

Why is this happening?

question from:https://stackoverflow.com/questions/65894691/comparisons-in-c-vs-vb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C, strings are just arrays of chars, which translates into a char pointer.

So, to compare strings, you must use the function strcmp.

Your code should then be the following

strcmp(over18, "Y") != 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...