Take sentence from user input with C - arrays

I wana take input from user and then print, I think I should also allocate memory could someone show me how to do that properly?
Here is my try:
int days = 1;
char * obligation[1500];
char * dodatno[1500];
puts("Enter nuber of days till obligation:\n");
scanf(" %d", &days);
puts("Enter obligation:\n");
scanf(" %s", obligation);
puts("Sati:\n");
scanf(" %s", dodatno);
printf("%s|%s|%s \n",days,obligation,dodatno);

You don't need to allocate dynamically. Just store it in a char array.
And printf("%s|%s|%s.... is wrong in your case, change the first %s to %d
Here is an example of how that would look like
int main()
{
int days = 1;
char obligation[256];
char dodatno[256];
printf("Enter number of days till obligation: ");
scanf("%d", &days);
printf("Enter obligation: ");
scanf("%s", obligation);
printf("Sati: ");
scanf("%s", dodatno);
printf("%d | %s | %s", days, obligation, dodatno);
return 0;
}
Otherwise, if you want to read in the whole line, you could use fgets and parse using strtok:
char* days;
char* obligation;
char* dodatno;
char line[256];
printf("Enter days, obligation and sati: ");
fgets(line, sizeof(line), stdin);
days = strtok(line, " ");
obligation = strtok(NULL, " ");
dodatno = strtok(NULL, "\n");
printf("%s | %s | %s", days, obligation, dodatno);
return 0;

Related

printf not printing integer stored in variable

For some weird reason when I input the values in the marks section, the printed values are all 0, please help, I tried running a smaller version of the code and it worked I don't know why this doesn't.
here is the code:
Stack overflow keeps giving me an error since apparently most of my question is code so pls ignore this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int marksComm;
char gradeComm[1];
int marksEco;
char gradeEco[1];
int marksCompsys;
char gradeCompsys[1];
int marksProg;
char gradeProg[1];
int marksDis;
char gradeDis[1];
int marksLab;
char gradeLab[1];
int marksPhy;
char gradePhy[1];
printf("CCS001\nMarks> ");
scanf("%d", &marksComm);
printf("Grade> ");
scanf("%s", &gradeComm);
printf("\nCCS009\nMarks> ");
scanf("%d", &marksEco);
printf("Grade> ");
scanf("%s", &gradeEco);
printf("\nCSC111\nMarks> ");
scanf("%d", &marksCompsys);
printf("Grade> ");
scanf("%s", &gradeCompsys);
printf("\nCSC112\nMarks> ");
scanf("%d", &marksProg);
printf("Grade> ");
scanf("%s", &gradeProg);
printf("\nCSC113\nMarks> ");
scanf("%d", &marksDis);
printf("Grade> ");
scanf("%s", &gradeDis);
printf("\nCSC126\nMarks> ");
scanf("%d", &marksPhy);
printf("Grade> ");
scanf("%s", &gradePhy);
printf("\nCSC115\nMarks> ");
scanf("%d", &marksLab);
printf("Grade> ");
scanf("%s", &gradeLab);
printf("\nCourse Code Marks Grade\n");
printf("CCS001 %d %s \n", marksComm, gradeComm);
printf("CCS009 %d %s \n", marksEco, gradeEco);
printf("CSC111 %d %s \n", marksCompsys, gradeCompsys);
printf("CSC112 %d %s \n", marksProg, gradeProg);
printf("CSC113 %d %s \n", marksDis, gradeDis);
printf("CSC115 %d %s \n", marksLab, gradeLab);
printf("CSC126 %d %s \n", marksPhy, gradePhy);
}
Your arrays are two small. C strings are NUL-terminated, so you need a char for the letter, and a char for the NUL. That's two char. But you reserve space for one.

First %s scanf value get ignore but second %s can store the value

int main()
{
char i;
char s;
printf("Enter first char : ");
scanf("%s", &i);
printf("Enter second char : ");
scanf("%s", &s);
printf("%c", i);
printf("%c", s);
}
The output turn out only print second scanf value while the first scanf value does not print out.
int main()
{
char i;
char s;
printf("Enter first char : ");
scanf("%c", &i);
printf("Enter second char : ");
scanf(" %c", &s);
printf("%c", i);
printf("%c", s);
}
When change to use %c both scanf value can be print out.
Why does the %s only store the last input while the first get ignored?
%s is to scan string :
scanf(" %s",&string);
Or
scanf("%s[^\n]",string);
%c to scan only one caracter :
scanf(" %c",&caracter);
in your first code ,if you want to read two string and print them :use this code
#include <stdio.h>
int main()
{
char i[150];
char s[150];
printf("Enter first char : ");
scanf("%s[^\n]",i);//scan the first string
printf("Enter second char : ");
scanf("%s[^\n]",s);//scan the second string
printf("%s", i);
printf("\n");
printf("%s", s);
printf("\n");
printf("%c",i[1]);//if you want to print the second caracter in the string i
printf("\n");
printf("%c",s[0]);//if you want to print the first caracter in the string s
}

Why does consecutive fgets accept input but stores it as a different or blank data when printed in a loop?

I'm a beginner at coding and I'm having trouble with using fgets because it accepts the input that I place but when I try to output it using printf then it isn't the right input.
I'm sorry if the answer is obvious but I've been stuck on this problem for an hour.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int eh;
char name[32];
char idnum[32];
char coursename[9][20];
int numberofcourses;
int unit[9];
float grade[9];
}information;
int main(){
char id[32];
char course_name[12];
information info[21];
char buf[3];
int numberofstud;
printf("Enter Number of Students:");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%d", &numberofstud);
fflush(stdin);
for(int i=0; i<numberofstud;i++){
printf("Enter UP Student Number:");
fgets(info[i].idnum, sizeof info[i].idnum, stdin);
printf("Enter Name:");
fgets(info[i].name, sizeof info[i].name, stdin);
printf("Enter Number of Enrolled Courses:");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%d", &info[i].numberofcourses);
getchar();
for(int j=0; j<info[i].numberofcourses;j++){
printf("Enter Course Name:");
fgets(buf, sizeof info[i].coursename[j], stdin);
sscanf(buf, "%s", &info[i].coursename[j]);
printf("Enter Course Units:");
fgets(buf, sizeof info[i].unit[j], stdin);
sscanf(buf, "%d", &info[i].unit[j]);
printf("Enter Course Grade:");
fgets(buf, 5, stdin);
sscanf(buf, "%f", &info[i].grade[j]);
getchar();
}
}
for(int i=0; i<numberofstud;i++){
printf("%s", info[i].idnum);
printf("%s", info[i].name);
for(int j=0; j<info[i].numberofcourses;j++){
printf("%s, %d, %.3f", info[i].coursename[j], info[i].unit[j], info[i].grade[j]);
}
}
return 0;
}
This is an example of what happens when I try to run the program
Sample Output:
Enter Number of Students:1
Enter UP Student Number:412412
Enter Name:Martinez
Enter Number of Enrolled Courses:1
Enter Course Name:CMSC 11
Enter Course Units:2
Enter Course Grade:3
412412
CMSC, 2, 3.000
I also don't mind if you point out any mistakes or bad practices in my code so that I can keep improving! Thank you for your time.
Putting a newline character in you final print fixed the issue for me. Also #Jonathan Leffer's comment is true, you'll likely chop your input or overrun a buffer keeping it so small like that, best to give more room than likely needed if memory space isn't a constraint.
With that said, I cleaned it up a little and added those newlines, the following code appears to function as intended. I also commented out some getchar calls and a fflush, if those were a mistake to remove I left them in just un-comment them.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int eh;
char name[32];
char idnum[32];
char coursename[9][20];
int numberofcourses;
int unit[9];
float grade[9];
}information;
int main(){
char id[32];
char course_name[12];
information info[21];
char buf[32]; //Increased your buffer size
int numberofstud;
printf("Enter Number of Students:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf, "%d", &numberofstud);
//fflush(stdin);
for(int i=0; i<numberofstud;i++){
printf("Enter UP Student Number:");
fgets(info[i].idnum,sizeof(info[i].idnum),stdin);
printf("Enter Name:");
fgets(info[i].name,sizeof(info[i].name),stdin);
printf("Enter Number of Enrolled Courses:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf, "%d", &info[i].numberofcourses);
//getchar();
for(int j=0; j<info[i].numberofcourses;j++){
printf("Enter Course Name:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf, "%s", &info[i].coursename[j]);
printf("Enter Course Units:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf, "%d", &info[i].unit[j]);
printf("Enter Course Grade:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf, "%f", &info[i].grade[j]);
//getchar();
}
}
for(int i=0; i<numberofstud;i++){
printf("%s\n", info[i].idnum);
printf("%s\n", info[i].name);
for(int j=0; j<info[i].numberofcourses;j++){
printf("%s, %d, %.3f", info[i].coursename[j], info[i].unit[j], info[i].grade[j]);
}
}
return 0;
}

String and for loop [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I wrote this C program to enter names and ages of 3 people. But the output wasn't my expectation. It was able to enter name and age for the first person, but it wasn't able for second and third persons. Please help.
#include <stdio.h>
#include <string.h>
int main()
{
int i, age;
char name[20];
for(i=0; i<3; i++)
{
printf("\nEnter name: ");
gets(name);
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
}
return 0;
}
In short: Your 2nd puts is processing the '\n' from your scanf.
Fix by adding getchar(); after scanf
Explanation:
1st iteration:
printf("\nEnter name: ");
gets(name); // line is read from input
printf("Enter age: ");
scanf(" %d", &age); // a number is read from input, and the newline char ('\n') remains in buffer
puts(name);
printf(" %d", age);
2nd iteration:
printf("\nEnter name: ");
gets(name); // previously buffered newline char is read, thus "skipping" user input
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
Same goes for 3rd iteration, and this is why you lose user input
The best way to store information of more than one person is to use struct, like
struct person {
int age;
char name[20];
};
and make array of struct, like
struct person people[3];
than use loop with accessing people[i].age and people[i].name, e.g.:
#include <stdio.h>
#include <string.h>
struct person {
int age;
char name[20];
};
#define ARR_SIZE 3
int main(int argc, char* argv[])
{
struct person people[ARR_SIZE];
int i;
char *lastpos;
for(i = 0; i < ARR_SIZE; i++)
{
printf("\nEnter name: ");
scanf(" %s", people[i].name);
if ((lastpos=strchr(people[i].name, '\n')) != NULL) *lastpos = '\0'; // remove newline from the end
printf("Enter age: ");
scanf(" %d", &people[i].age);
}
printf("This is the people you entered:\n");
for(i = 0; i < ARR_SIZE; i++)
{
printf("%d : %s : %d\n", i+1, people[i].name, people[i].age);
}
return 0;
}
UPDATE:
As you see I use scanf(" %s", people[i].name); instead of gets(people[i].name); to read name from stdin. Try both option for the following cases:
enter short name (e.g. John) and correct age (e.g. 15)
enter two word name (e.g. John Smith) and correct age (e.g. 17)
enter short name and uncorrect age (e.g. five)
Then read articles about value returned by scanf and cleaning input buffer

C program, designing a check

I'm writing a program that basically just takes a bunch of user input and Outputs it in the form of a check. My problem is that I'm entering 2 sentences and while the second one is fine it completly skips the first one! and the user last name is working but the first name just outputs "z" it is the weirdest thing and my teachers philosophy is figure it out yourself. So can anyone possibly help me?? Here is my code...
#include<stdio.h>
#include<string.h>
int main()
{
char date[8];
int checkNum;
char payeeFirst[10];
char payeeLast[10];
double amount;
char memo[50];
char wordAmount[100];
printf("Please enter the date: ");
scanf("%s", &date);
printf("Please enter the check number: ");
scanf("%d", &checkNum);
printf("Please enter the payee First name: ");
scanf("%s", &payeeFirst);
printf("Please enter payee last name: ");
scanf("%s", &payeeLast);
printf("Please enter amount: ");
scanf("%d", &amount);
printf("Please enter amount in words: ");
fgets (wordAmount, sizeof(wordAmount)-1, stdin);
printf("Please enter memo: ");
fgets (memo, sizeof(memo)-1, stdin);
printf(" \n");
printf("Date: %s .\n", date);
printf("Check Number: %d .\n", checkNum);
printf("Payee: [%s] [%s] .\n", payeeFirst, payeeLast);
printf("Amount: %d .\n", amount);
printf(" Check %d \n", checkNum);
printf(" Date: %s \n", date);
printf("Pay to the\n");
printf("Order of %s %s $%d \n", payeeFirst, payeeLast, amount);
printf("%s", wordAmount);
printf(" \n");
printf(" \n");
printf("Memo: %s \n", memo);
return 0;
}
Your scanf calls all leave the '\n' in the stream (the next scanf will ignore it though).
The first fgets reads an empty string (well ... a string containing a single '\n').
Try reading the numbers with fgets too (to a temporary buffer) and sscanf from the buffer to the correct variable. This way all the '\n' will be accounted for.

Resources