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
229 views
in Technique[技术] by (71.8m points)

C program prints out wrong values

I made a simple code to scan for user input and print it out. It only outputs the first character if its a string an gives me wrong values if its integers. The code is written in C. I'm using codeblocks on ubuntu.

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

int main()
{   char name;
    int age;
    printf("Enter your name: 
");
    scanf("%c", &name);
    printf("Enter your age: 
");
    scanf("%d", &age);
    printf("Your name is %c and your age is %d", &name, &age);
    return 0;
}
question from:https://stackoverflow.com/questions/65651280/c-program-prints-out-wrong-values

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

1 Reply

0 votes
by (71.8m points)

you declared name as char, that can hold only 1 character, generally any name is more than 1 character, so what you need is an array char name[50], and use %s for reading it.

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

int main()
{   char name[50] = {0};
    int age;
    printf("Enter your name: 
");
    scanf("%49s", name);
    printf("Enter your age: 
");
    scanf("%d", &age);
    printf("Your name is %s and your age is %d", name, age);
    return 0;
}

& prints the address of the variables, you just need to use only variable names in printf

Collect the return value of scanf to check correct number of items are read


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

...