I have homework in my C programming class.
I have to input 3 people's information about name, major, ID(ex. 9304171)and output to console
'name, birth(yyyy-mm-dd), leep year, nationality, sex, major'.
I tried to that, but my scanf_s wasn't activated.
if i try to activate to my code, char array can activated, but my integer array can't activated.
char name[4]; // name
char major[4]; // major
int id[7] = {}; // ID
// Input name, major, ID
printf("Name : ");
scanf_s("%s \n", &name, 4);
printf("Major : ");
scanf_s(" %s \n", &department, 4);
printf("ID : ");
scanf_s("%d \n", id);
My English ability is so fool... but it is make me so angry, i begging to help..
plz, sombody help me T.T
Declare something like:
char name[50], major[50];
int id; // array removed
You can use fgets() if you're having issues with scanf_s(), I suspect you've given such short number of elements for name array (i.e. 4) and that's something relatable with the error. Try the following using fgets():
printf("Name: ");
fgets(name, 50, stdin); // fgets buffered for 50 elements
printf("Major: ");
fgets(major, 50, stdin); // fgets ...
printf("ID: ");
scanf("%d", &id); // scanf() can be used here
Let's take a look at a sample output (no errors):
// INPUT
Name: John Doe
Major: Something
ID: 101
// OUTPUT
Name: John Doe
Major: Something
ID: 101
Related
So I have a list of names and corresponding phone numbers, and I want the user to be able to continuously enter a new name-number pair into that list. The part of my code where I try to do that looks something like this:
char name[20], list_names[1000][20], phone[20], list_phone[1000][20];
int n;
n = 0;
do
{
printf("Enter name: ");
scanf("%20[^\n]", name);
printf("Enter phone number of %s: ", name);
scanf("%20[^\n]", phone);
strcpy(list_names[n], name);
strcpy(list_phone[n], phone);
n += 1;
}
while (n < 1000);
This usually gives me an error like "incompatible pointer type". I have to do it the indirect way and first store the name in a separate variable. But how do I get the string from that variable into the list? Probably there's something I don't get in the strcpy() part.
Thanks for helping out!
try this
printf("Enter name: ");
scanf(" %19[^\n]", name);//add one space and turn 20 to 19 (leave space for '\0')
printf("Enter phone number of %s: ", name);
scanf(" %19[^\n]", phone);
I'm trying to understand the whole concept of pointers, structures, etc so I've created a program that gets user input for two different books and then swaps the info of the two books. I had no trouble doing that, however, a problem arose- when I pressed enter the name of the book would be plain blank and at the output I would, of course, see a blank space. My problem is, how am I able to limit the user to input any letter (A-Z, a-z) and not blank space?
A string of characters when input to an array, they get saved in consecutive memory addresses. We also know that 'NULL' is represented as '\0' in arrays.
With the above things in mind, I performed multiple tests in which, ALL of them failed to yield the desired results.
Below are some attempts that I made.
1st Attempt
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
2nd Attempt
while (strcmp(pBook1->name, ""))
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
Also, consider the following code as the source code of my program:
#include <stdio.h>
#include <string.h>
#define MAX 50
struct Books
{
char name[MAX];
int ID;
float price;
};
void swap(struct Books *, struct Books *);
void main()
{
struct Books Book1, Book2, *pBook1, *pBook2;
pBook1 = &Book1;
pBook2 = &Book2;
// Input for the 1st book
printf("\n 1st Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook1->name, MAX, stdin);
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook1->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook1->price);
// Input for the 2nd book
printf("\n 2nd Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook2->name, MAX, stdin);
while (pBook2->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook2->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook2->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook2->price);
printf("\n Let's swap the info of the two books...");
swap(pBook1, pBook2);
printf("\n The info of the two books is now:");
printf("\n------------------------------ \n 1st Book \n ------------------------------------");
printf("\n Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook1->name, pBook1->ID, pBook1->price);
printf("\n------------------------------ \n 2nd Book \n ------------------------------------");
printf("Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook2->name, pBook2->ID, pBook2->price);
}
void swap(struct Books *pB1, struct Books *pB2)
{
char temp[MAX];
strcpy(temp, pB1->name);
strcpy(pB1->name, pB2->name);
strcpy(pB2->name, temp);
int tempID = pB1->ID, tempPrice = pB1->price;
pB1->ID = pB2->ID;
pB2->ID = tempID;
pB1->price = pB2->price;
pB2->price = tempPrice;
}
fgets reads until it encounters EOF, \n or N-1 bytes have been read. So if a user of your program presses enter, it will read \n and stop. Which means that pBook1->name[0] == '\n'. That is why your check for equality with "" fails and why pBook1->name[0] == '\0' fails.
See this example.
That means that you need to check for \n and \0 in case the user entered Ctrl-D which is how you enter EOF on *nix systems.
When you press enter pBook1->name[0] will become \n. You can use some functions as strlen to be sure there something in name.
#include <stdio.h>
#include<stdlib.h>
int main()
{
char first[10], last[10], id[10];
int stdnum;
FILE *fptr;
fptr = fopen("C:\\c\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
else
{
//first name
printf("Enter name: ");
scanf("%s", first);
fprintf(fptr,"%s ",first);
//last name
printf("Enter last name: ");
scanf("%s ", last);
fprintf(fptr,"%s", last);
//id
printf("Enter id: ");
scanf("%s %d", id, &stdnum);
fprintf(fptr,"%s\n", id);
fprintf(fptr,"%d\n", stdnum);
fclose(fptr);
return 0;
}
}
I am writing a program that asks user for name, last name and student number. Student number format is lowercase letter followed by 8 digits.
when i run this code, I can enter first and last name. After i enter last name and hit enter in cygwin, the console gives me a blank line and I MUST type atleast a charcter or a number into it for it to display "enter student id".
Enter name: bob
Enter last name: jones
1
Enter id: a00998877
then the file output is something like this:
"bob jones11"
I want the output to be something like this:
"Bob Jones a00998877"
What am i doing wrong?
Why are you scanning in two inputs in this line:
scanf("%s %d", id, &stdnum);
id is a char array and will be able to hold alphanumeric input. You can remove the use of stdnum.
scanf("%s", id);
I have an example-with-stdin-stdout
char first[10], last[10], id;
id is a single char no need for an array.
scanf("%s", last);
Removed space after s
scanf(" %c%d", %id, &stdnum)
changed id to char from string
fprintf(fptr,"%c\n", id)
Same here, changed to char
Is it possible to read a character and an integer in one time?
Like this:
char name[32];
int age;
printf("Give name and age: ");
scanf("%s%d%*c", name, &age);
It blocks all the time.
UPDATED: You only accept input but not printing any thing. See the below code ( working and tested )
#include <stdio.h>
int main(void) {
char name[32];
int age;
printf("Give name and age: ");
scanf("%31s%d", name, &age);
printf("Your name is %s and age is %d",name,age);
}
intput: Shaz 30
Output : Your name is Shaz and age is 30
char name[32];
int age;
printf("Give name and age: ");
scanf("%31s%d", name, &age);
If the input string is longer than 31 characters, the value read for age will be affected, this is where fgets comes in handy.
Do not read both the name and age on the same line input. Read the name first to force the user to enter a new line so you can handle the entire line as the input name.
Read fgets
It is one of the method
CODE
#include<stdio.h>
char name[32],age;
int main()
{
printf("Enter name and age: ");
scanf("%s%d", name, &age);
printf("\nNAME : %s AGE : %d",name,age);
}
OUTPUT Refer under the image
I have tested your code, there is no error. Maybe you should only add printf() to print the answer.You will find you can get the same answer with what you have printed.
EDIT: If input is Colin 23(the space is necessary), you should use printf("name is %31s, age is %d", name, age). Then you will get output Colin 23.
You can do it like this:
#include <stdio.h>
int main(void)
{
char name[32];
int age;
printf("Give name and age: ");
scanf("%s%d", name, &age);
printf("%s\n",name);
printf("%d",age);
}
This question already has answers here:
Why is getchar() reading '\n' after a printf statement?
(3 answers)
Closed 9 years ago.
This is a newbie question. I am new to C programming. I have the following code which does not prompt for 'Name' Onece the 'Age' is entered, it bypass the 'Name section.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
printf("Enter age : ");
scanf("%d", &age);
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
After reading first prompt it bypass the second prompt which is using getchar() function. But if I change the order of prompt to ask for 'Name' first and then 'Age' it works fine.
The working code.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Enter age : ");
scanf("%d", &age);
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
My coding IDE is CodeBlock and my compiler is GNU C Compiler (mingw32-gcc.exe)
Please help me to breakthrough.
A few improvements/advices to the code in the question:
the type of the return value of getchar() is int, so the type of ch also should be int
you could (and should, I believe) use format %s to read the name, this is easier and the leading white spaces in the input stream would not be a problem
the user of the code could give a name which contains more than 30 characters, and this input could crash your program, so you should protect your code for this possibility. You have two options:
a. use format '%29s" to read the name
b. change the definition of name to char *name, read it by scanf("%ms", &name);, and call free(name); after you do not need it anymore
Here is an example, in which the name can be very long and can include spaces:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
char *name;
int age;
printf("Enter name: ");
scanf("%m[^\n]", &name);
printf("Enter age: ");
scanf("%d", &age);
printf("Name: %s\n", name);
printf("Age : %d\n", age);
free(name);
exit(EXIT_SUCCESS);
}
And here is a run of it:
$ ./a.out
Enter name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Enter age: 12
Name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Age : 12
In first code the \n character left behind by the scanf is read by getchar. This makes the condition (ch = getchar())!='\n' in while loop false and the loop body never get executed.
You need to consume that \n character which comes up to the buffer along with the age you entered on pressing Enter key.
Putting the statement
while(getchar()!='\n');
after the scanf will consume all of the newline characters.
Your second code is working fine because %d skips white-space characters unlike %c specifiers.