如何在C编程中控制'char'类型的用户输入?

时间:2017-10-21 07:12:01

标签: c string io char scanf

如何在C编程中控制char类型的用户输入?

问题:如果用户将“男性”作为第一个输入,那么程序就不会要求“年龄”

输出

输入性别(男/女):男

输入年龄:

你的性别是男性(M)

您的年龄:71 //垃圾值

#include <stdio.h>

int main()
{
    char gender;
    int age;

    printf("\nEnter gender(M/F):");
    scanf("%c", &gender);

    printf("\nEnter age:");
    scanf("%d", &age);

    if(gender=='M'){
        printf("\nYour Gender is Male(%c)",gender);
    }else{
        printf("\nYour Gender is not Male(%c)",gender);
    }

    printf("\nYour Age a:%d",age);

    return 0;
}

预期输出:如果用户输入'男'/'女'/'M'/'F'然后按Enter键 然后控制台会要求给予年龄

输入性别(男/女):男

输入年龄:23​​

您的性别是男性(M)//基于和性别

你的年龄:23​​

2 个答案:

答案 0 :(得分:1)

你想阅读一个刺痛,但你正在使用一个角色,所以将你的代码更改为:

char gender[7];
scanf("%6s", gender);
...
if (gender[0] == 'm' || gender[0] == 'M')
    printf("\nYour Gender is Male(%c)", gender[0]);
...

第二个解决方案:

只需使用fgets()表示性别,因为您希望能够读取字符串,然后scanf()查看年龄,如下所示:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char gender[7];
    printf("Enter gender(M/F): ");
    if (!(fgets(gender, sizeof(gender), stdin) != NULL)) {
        fprintf(stderr, "Error reading Gender.\n");
        exit(1);
    }
    gender[strcspn(gender, "\n")] = 0;
    int age;
    printf("\nEnter age:");
    scanf("%d", &age);

    if (gender[0] == 'm' || gender[0] == 'M')
        printf("\nYour Gender is Male(%c)", gender[0]);
    else if (gender[0] == 'f' || gender[0] == 'f')
        printf("\nYour Gender is Female(%c)", gender[0]);
    else
        printf("Unrecocognized gender\n");
    printf("\nYour Age is: %d\n",age);

    return 0;
}

输出:

Enter gender(M/F): f
Enter age: 25
Your Gender is Female(f)
Your Age is: 25

答案 1 :(得分:-2)

使用gets()或char数组和Strcmp()来比较字符串。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Socket sock = null;
    InputStreamReader is;
    BufferedInputStream bis;
    PrintWriter pw;
    try {

        sock=new Socket("10.0.0.2",6667);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
        out.write("hjdhfsjd");
        //send output msg
        pw=new PrintWriter(sock.getOutputStream());
        pw.write("msg sent once");

        pw.flush();
        out.flush();
        out.close();
        pw.close();
        sock.close();

        System.out.println("dfsdjf");
    }
    catch (Exception e)
    {

    }

}