I want to execute this code to run auto taskscheduling as this code has two errors. I'm not able to figure out the corrections.
Errors are "(in function 'main')" and "(invalid lvalue in assignment)"
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main()
{
char *timetoken;
char currtime[7];
char schedtime[9];
int i;
struct tm *localtimeptr;
strcpy(schedtime,"15:25:00");
while(true)
{
time_t lt;
sleep(1);
time(<);
localtimeptr = localtime(<);
timetoken=strtok(asctime(localtimeptr)," ");
for(i=1;i<5;i++)
timetoken=strtok(NULL," ");
if(i==3)
{
strcpy(currtime,timetoken);
}
}
printf("The current time is: %s\n",currtime);
printf("We are waiting for: %s\n",schedtime);
if(!strcmp(currtime,schedtime))
{
printf("Time to do stuff \n");
system("ROBOCOPY C:\\oslab E:\\BACKUP /e/mir/np /log:backup_log.txt");
}
getch();
return 0;
}
time = (<);
You didn't define a variable called time... are you sure this wasn't meant to set a different variable?
time = (<);
You're trying to assign to time, but you yourself have never declared anything called time. Accordingly, you're trying to reassign time(3) from time.h.
Maybe you mean something else in this line, like
time(<);
Related
I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.
The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
int num;
char code[5];
}fl;
fl flight[9999];
int Valid(char a[], int b)
{
if((strlen(a) != 4) || (b<0 || b>9999)){
return 0;
}
else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
return 0;
}
return 1;
}
void opt1(fl a[]){
char tempCode[5];
int tempNum;
do
{
puts("Insert code:");
fgets(tempCode, 5, stdin);
scanf("%d", &tempNum);
puts("");
if (Valid(tempCode, tempNum))
{
printf("Flight %s%d registered. \n", tempCode, tempNum);
}
else
{
puts("Flight # invalid.");
}
} while (Valid(tempCode, tempNum)==0);
}
int main() {
int opt;
//calling opt1 works as intended
opt1(flight);
//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);
if(opt==1){
opt1(flight);
}
return 0;
}
And here's an input:
FLI-1234
1
FLI-1234
That returns:
Flight FLI-1234 registered.
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.
I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.
I am a C beginner and trying this and that.
I want to display a string letter by letter with tiny pauses in between. So my idea was a small pause using sleep or usleep after displaying each char but I read that using nanosleep in your own function makes more sense. So I put my little pauses in a function "msleep" to get microseconds pauses.
I output my string 3 times.
Once in the main(), then in a do-while-loop in a function (fancyOutput) char by char, and eventually in the same function with printf again to check, if it was handled over correctly.
My problem: I expected, that the middle output would work char by char and separated by 100/1000 seconds breaks, but what I experience is a long break before chowing any char and then a fast output if line two and three. It looks like the compiler "realized what I am planning to do and wants to modify the code to be more efficient." So all my pauses seemed to be combined in one long break.
Maybe you remeber the captions in the tv series "x files" - something like that I want to produce.
For sure there are better and more sophisticated ways to archieve what I am going to try but I want to learn and understand what is going on. Can someone help me with that?
I am using codeclocks on a debian-based distro with gcc.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
You are getting problem with buffer.
When you use printf with no \n (new line) C is buffering the display in order to display information block by block (to optimize displaying speed).
Then you need to either add a \n to your printf or add a flush of the stdout.
An other solution will be to use stderr, which got no buffer, but stderr is meant for error not output :)
You can also check setvbuf in order to change the buffering.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
flush(stdout);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
So, I tried the solution to place fflush(stdout); directly after the char-output in the loop. It worked as intended.
Summarizing for those with similar problems (guess this also happens with usleep and similar self-made functions):
As I understaood, printf "collects" data in stdout until it "sees" \n, which indicates the end of a line. Then printf "releases" stdout. So in my initial post it "kept" each single char in stdout, made a pause after each char and finally released stdout in one fast output.
So fflush(stdout); after each char output via empties stdout char by char.
Hope it can help others.
The following program is supposed to ask the user how many students he wants to grade then have the user input the grades and get the average.
#include <stdio.h>
#include <stdlib.h>
struct person {
char Name[100];
int ID;
int Age;
double Score;
};
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
int size;
printf("How many students are you grading?(Not more than 100)-->");
scanf("%d",&size);
struct person *student;
double total=0,i=0, average;
student= malloc(sizeof(struct person));
//struct person student;
printf("Enter the following information:\n");
while (i<size) {
printf("%lf\n%lf\n",total,i);
printf("\n");
printf("Name:");
scanf("%s",student->Name);
printf("ID:");
scanf("%d",&student->ID);
printf("Age:");
scanf("%d",&student->Age);
printf("Score:");
scanf("%lf",&student->Score);
total = total + student->Score;
i++;
}
The code works fine until it needs to print out the average based on user input, at which point the program terminates without giving the average nor an error message.
if(size==1){
average = total / size;
printf("Class average is %0.2lf\n", average);
}
else
{
average=total/i;
printf("Class average is %0.2lf\n", average);
}
return 0;
}
Most console programs are intended to be run from some kind of console host like windows cmd, where the output stays there and it would be annoying for user to do some additional work to end the program so they can run another command, but since you are just testing it, you should put some code at the end to wait for some user input, now there are many ways to do that like: getch(), getchar(), scanf("%*c"), system("pause") so you can try those, but some compilers do this automatically in debug mode, sometimes you just need to specify the behaviour in your IDE settings.
I think the problem you are having is that the console is closing before you can read the average.
You could add:
getchar();
Before you return 0; in int main.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
double gen(double dS) //Function for a random double variable
{
double dx=0;
dx=rand()%200+1;
dS=dx/100;
return(dS);
}
int main()
{
double dZahl=0;
double dTokens=1;
srand((unsigned)time(NULL));
double dSummand=0;
int iGame=0;
for(;;)
{
printf("Deine Tokens:%.2lf\n", dTokens); //This doesn't really matter
printf("Was m%cchtest du tun?\n[1]:Generiere Tokens\n[2]:Spiele ein Minigame\n", 148);
fflush(stdout);
scanf("%d", &iGame);
fflush(stdin);
switch (iGame)
{
case 1:
{
gen(dSummand); //function in use
dTokens=dTokens+dSummand;
printf("\nDu hast %.2lf Tokens generiert!\n", dSummand); //the output of the value
fflush(stdout);
}
break;
}
}
getch();
}
The problem is that dSummand doesn't get the value from dS. Does anyone know what the problem is because I was trying to fix it but I couldn't figure it out.
I am trying to get a random double value with a function for my program. I thought it would work like this but unfortunately it didn't.
If you want the value for dS to come out of the function modified you have to pass a pointer.
double gen(double *dS) {
*dS=dx/100;
and then
gen(&dSummand);
I am currently trying to store information that is input from a function to a struct declared in my header file and utilize it within the main file. I cannot use struct arrays because I am not allowed to allocate memory.
header file
#ifndef HOMEWORK_H_
#define HOMEWORK_H_
typedef struct
{
int CourseID[25];
char CourseName[100][25];
}Course;
void NewCourse(void);
#endif
My code
#include <stdio.h>
#include <stdlib.h>
#include "Homework.h"
void NewCourse()
{
int i;
int CNumber = 0;
Course storeC;
for(i = 0; i < 0; i++)
{
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i;
break;
}
}
}
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
}
and my main does not really apply since the problem lies within storing the data.
A few things to keep in mind is I must utilize a separate file for my functions and I must use a header file for my structs.
I know my for loop to determine where in the array may not be effective, but I am not so worried about it as of right now.
My question is how do I store the data from this function to the
header file?
Update
I changed the main function to fit everything else and I end up with this error now.
a label can only be part of a statement and a declaration is not a
statement
The code in main is:
switch(Option)
{
case 1:
Course c = NewCourse();
printf("%d\n%s\n", c.CourseID[0], c.CourseName[0]); // For testing purposes
break;
What is causing the error because it says it stems from line 29 which is the Course c = NewCourse();?
Change NewCourse to return a Course.
Course NewCourse(void);
Change the implementation to:
Course NewCourse()
{
int i;
int CNumber = 0;
Course storeC;
...
return storeC;
}
Change main accordingly.
int main()
{
Course c = NewCourse();
}
PS
You said,
I cannot use struct arrays because I am not allowed to allocate memory.
I assume that to mean that you cannot use dynamic memory allocation. If you are allowed to create an array of structs in the stack, you can simplify your code by using:
typedef struct
{
int CourseID[25];
char CourseName[100];
}Course;
void NewCourse(Course course[]);
and in main, use:
Course courses[25];
NewCourse(courses)
In response to your update
You needed to add a scope block { } around the code as follows:
int main()
{
{
Course c = NewCourse();
}
}
This should resolve your error and allow your code to compile.
Additionally, you have an error in manipulating the CNumber Variable. It is declared twice, with different scopes:
int CNumber = 0; // the first definition with the scope of the NewCourse Function
Then inside the test, with a block scope:
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i; // block-scope. This is not the same CNumber Variable (todo: Omit int)
break;
}
}
As a result, when you reference it later in
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
It will be always reference the function scope variable, which is always be zero.
Solution: omit the int declaration inside the test:
if(storeC.CourseName[i] == NULL)
{
CNumber = i;
break;
}