When I run the program the first for loop works just fine but then I get the "Program has stopped working" message before going into the second while loop. Is there an error in my coding and if so how can I fix it?
#include<stdio.h>
double Combat(int x, int y, char mons[20]);
int main(void)
{
int monsters, i, target, alive;
while(1)
{
printf("ENTERING COMBAT\n\nHow many monsters?> ");
scanf(" %d", &monsters);
char monster[monsters][20];
int monstermaxhp[monsters];
int monsterhp[monsters];
for(i=0;i<monsters;++i)
{
printf("\n\nNO SPACES\n\nEnter Monster %d's name> ", i+1);
scanf("%s", &monster[i]);
printf("\n\nEnter %s's hitpoints> ", monster[i]);
scanf("%d", &monstermaxhp[i]);
monsterhp[i]=monstermaxhp[i];
}
alive=1;
while(alive==1)
{
for(i=0;i<monsters;++i)
{
printf("\n\n%d:%s%3c%3d/%d", i+1, ' ',monsterhp[i],monstermaxhp[i]);
}
printf("\n\nSelect Target> ");
scanf("%d", &target);
i=target-1;
monsterhp[i]=Combat(monsterhp[i],monstermaxhp[i],monster[i]);
for(i=0;i<monsters;++i)
{
if(monsterhp[i]<=0)
alive=0;
}
}
}
return(0);
}
double Combat(int x, int y, char mons[20])
{
int damage, plrroll, monroll;
printf("\nRoll for %s> ", mons);
scanf("%d", &monroll);
printf("\nRoll for Player> ");
scanf("%d", &plrroll);
if(plrroll>monroll)
{
printf("\nHIT! Roll for damage> ");
scanf("%d", &damage);
x=x-damage;
}
else
{
printf("\nMISS! :P\n");
}
return(x);
}
Change:
printf("\n\n%d:%s%3c%3d/%d", i+1, ' ',monsterhp[i],monstermaxhp[i]);
to
printf("\n\n%d: %s %3d/%d", i+1, monster[i], monsterhp[i], monstermaxhp[i]);
You're trying to printf in the wrong order. I think you missed out the monster's name! There's no need for the 3 spaces using %c either, so I've inlined the spaces in your format string instead.
You now get an output like:
1: Good 1/1
2: Evil 2/2
Ok just a few problems with your code :
you are declaring arrays : monster,monstermaxhp and monsterhp everytime you loop in outer while
its not return(0); .. its return 0;
in for loop do post increment ( change ++i to i++)
Fix your printf statement to this:
printf("\n\n%d:%s%3c%3d/%d", i+1, monsterhp[i], ' ', monstermaxhp[i]);
Also change :
scanf("%s", &monster[i]);
to this:
scanf("%s", monster[i]);
Related
I have faced a problem with my program and I don't understand why. I read 2 data string and the program just skips the first read and jumps on the second one. I can't place the program here because is pretty big and I don't think anyone wants to waste time reading and understanding it.For example:
struct agenda {
char nume[20];
char prenume[20];
} vector[50];
void adaugare (){
printf("x=");
gets_s(vector[0].nume);
printf("y=");
gets_s(vector[0].prenume);
}
And when I build and run it, it only reads the second string.Edit:
struct agenda {
char nume[20];
char prenume[20];
}vector[50];
void adaugare();
void main() {
adaugare();
_getch();
}
void adaugare() {
int numar;
system("cls");
printf("\n\tCate contacte doriti sa adaugati? ");
scanf_s("%d", &numar);
for (int i = 0; i < numar; i++) {
printf("\nIntroduceti contactul %d\n", i);
printf("\tIntroduceti numele contactului %d: ", i);
gets_s(vector[i].nume);
printf("\tIntroduceti prenumele contactului %d: ", i);
gets_s(vector[i].prenume);
}
}
So in this case if you build and run it, it only reads the second string.
First thing you should elaborate what is gets_s() ? Is it your implementation of gets() or typo ? Instead of gets_s use fgets() to avoid buffering problem as mentioned in comments by #user3121023
// gets_s(vector[0].nume);
fgets(vector[0].nume,sizeof(vector[0].nume),stdin);
printf("y=");
// gets_s(vector[0].prenume);
fgets(vector[0].prenume,sizeof(vector[0].prenume),stdin);
EDIT(for visual c++) :
void adaugare() {
int numar;
system("cls");
printf("\n\tCate contacte doriti sa adaugati? ");
scanf_s("%d", &numar);
fflush(stdin);
for (int i = 0; i < numar; i++) {
printf("\nIntroduceti contactul %d\n", i);
printf("\tIntroduceti numele contactului %d: \n", i);
fflush(stdin);
gets_s(vector[i].nume);
printf("\tIntroduceti prenumele contactului %d: \n", i);
fflush(stdin);
gets_s(vector[i].prenume);
}
}
Because You must flush the input buffer(stdin) before using gets_s().
I hope it help's.
Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}
my program is supposed to implement a dfa for a binary string... dfa is a machine that can be in only one state at a time (when you enter a string the machine should use it and at the last step it should reach to the final state. if so, we say that string is accepted by the machine) ...
this machine works this way:
at first program asks the number of states, if u consider my pic, u see that it has 3 states(q0,q1,q2) so we enter 3. then it asks about the number of inputs. my inputs are 0,1 so I enter 2... then it asks to enter the inputs, we enter 0 then 1! then it asks the number of final states, the final state here is only q1... so we enter it... then u see this: (q0,0) = q it means q0 goes to which state with 0... for example here q0 goes to q0 with 0 ... others are like that. after filling this part, we enter the sring and it would say if string is valid or not
here is the code:
#include<stdio.h>
#include<conio.h>
int ninputs;
int check(char,int ); //function declaration
int dfa[10][10];
char c[10], string[10];
int main()
{
int nstates, nfinals;
int f[10];
int i,j,s=0,final=0;
printf("enter the number of states that your dfa consist of \n");
scanf("%d",&nstates); // 3
printf("enter the number of input symbol that dfa have \n");
scanf("%d",&ninputs); // 2
printf("\nenter input symbols\t");
for(i=0; i<ninputs; i++)
{
printf("\n\n %d input\t", i+1);
printf("%c",c[i]=getch()); // 01
}
printf("\n\nenter number of final states\t");
scanf("%d",&nfinals); // 1
for(i=0;i<nfinals;i++)
{
printf("\n\nFinal state %d : q",i+1);
scanf("%d",&f[i]); // 1
}
printf("-----------------------------------------------------------------------");
printf("\n\ndefine transition rule as (initial state, input symbol ) = final state\n");
for(i=0; i<ninputs; i++)
{
for(j=0; j<nstates; j++)
{
printf("\n(q%d , %c ) = q",j,c[i]);
scanf("%d",&dfa[i][j]);
// q(0,0)=0
// q(1,0)=0
// q(2,0)=2
// q(0,1)=1
// q(1,1)=2
// q(2,1)=1
}
}
do
{
i=0;
printf("\n\nEnter Input String.. ");
scanf("%s",string); // 01
while(string[i]!='\0')
{
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
{
if(f[i] ==s )
final=1;
if(final==1)
printf("\n valid string");
else
printf("invalid string");
getch();
printf("\nDo you want to continue.? \n(y/n) ");
}
}
}
while(getch()=='y');
getch();
}
int check(char b,int d)
{
int j;
for(j=0; j<ninputs; j++)
if(b==c[j])
return(dfa[d][j]);
return -1;
}
the problem is that when I enter my string, the program says it's invalid, however it should be accepted by the machine... for example consider the machine in the photo and test this string on it: 01
so what's wrong with the code?
Optimized C code for Accepting String using DFA
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int a,b,i,j,k,state,ch;
char s[10][10],*st,v[10],ss[10];
printf("Enter the number of state:\n");
scanf("%d",&a);
printf("Enter State :\n");
for(i=0;i<a;i++)
{
fflush(stdin);
scanf("%c",&ss[i]);
}
printf("Enter th no. of var..:\n");
scanf("%d",&b);
printf("Enter variable :\n");
for(i=0;i<b;i++)
{
fflush(stdin);
scanf("%c",&v[i]);
}
printf("Enter table:\n");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
fflush(stdin);
scanf("%c",&s[i][j]);
}
}
printf("Enter string :\n");
fflush(stdin);
gets(st);
i=0;
state=0;
while(st[i]!='\0')
{
for(j=0;j<b;j++)
{
if(st[i]==v[j])
{
if(s[state][j]=='-')
{
goto check;
}
else
{
for(k=0;k<a;k++)
{
if(s[state][j]==ss[k])
{
printf("State:%c\n",s[state][j]);
state=k;
goto o;
}
}
}
o:
}
}
i++;
}
check:
ch=1;
for(i=0;i<b;i++)
{
if(s[state][i]!='-')
{
ch=0;
}
}
if(ch==1)
{
printf("String is matching..");
}
else
{
printf("String is not matching..");
}
getch();
return 0;
}
Just put an space before %c . And edit some lines of the code.
This code is successfully complied on Code::Blocks 13.12 version.
As it C++ Compiler save the file with .cpp extension.
And Click On the " output image " . You will see how to input & output from
console
<--------Here Is the edited code && It will work fine ---> #
output image
#include<stdio.h>
#include<cstdio>
#include<iostream>
int ninputs,bb;
int check(char,int ); //function declaration
int dfa[10][10];
char c[10], string[10],b;
int main()
{
int nstates, nfinals;
int f[10];
int i,j,s=0,final=0;
printf("enter the number of states that your dfa consist of \n");
scanf("%d",&nstates);
printf("enter the number of input symbol that dfa have \n");
scanf("%d",&ninputs);
printf("\nenter input symbols");
for(i=0; i<ninputs; )
{
bb =i;
printf("\n %d input",bb+1);
// printf(" %c",c[i]=getchar());
scanf(" %c" , &c[i]); //just put an space before %c
i++;
}
printf("\n\nenter number of final states\t");
scanf("%d",&nfinals);
for(i=0;i<nfinals;i++)
{
printf("\n\nFinal state %d : q",i+1);
scanf("%d",&f[i]);
}
printf("-----------------------------------------------------------------------");
printf("\n\ndefine transition rule as (initial state, input symbol ) = final state\n");
for(i=0; i<ninputs; i++)
{
for(j=0; j<nstates; j++)
{
printf("\n(q%d , %c ) = q",j,c[i]);
scanf("%d",&dfa[i][j]);
}
}
do
{
i=0;
printf("\n\nEnter Input String.. ");
scanf("%s",string);
while(string[i]!='\0')
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
if(f[i] ==s )
final=1;
if(final==1)
printf("\n valid string");
else
printf("invalid string");
printf("\nDo you want to continue.? \n(y/n) ");
}
while(b =='y');
scanf(" %c", &b); // chnge here
}
int check(char b,int d)
{
int j;
for(j=0; j<ninputs; j++)
if(b==c[j])
return(dfa[d][j]);
return -1;
}
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
main()
{
int state,symbol;
char str[30];
cout<<"Enter the string which you want to check :: "<<endl;
fgets(str,sizeof(str),stdin);
cout<<"Enter the Number of state :: ";cin>>state;
cout<<"Enter the Number of input symbol :: ";cin>>symbol;
cout<<"Enter the states : "<<endl;
char st[state];
for(int i=0;i<state;i++)
{
cout<<"state : "<<i<<" : ";cin>>st[i];
}
cout<<"Enter the input symbol : "<<endl;
char sy[symbol];
for(int i=0;i<symbol;i++)
{
cout<<"symbol : "<<i<<" : ";cin>>sy[i];
}
char table[state][symbol];
cout<<"------Enter next move or state------ if no relation put -"<<endl;
for(int i=0;i<state;i++)
{
for(int j=0;j<symbol;j++)
{
cout<<"("<<st[i]<<", "<<sy[j]<<") = ";cin>>table[i][j];
}
}
char ststate,fnstate;
cout<<"Start state :: ";cin>>ststate;
cout<<"Final state :: ";cin>>fnstate;
cout<<"----------------------------------"<<endl;
int str_len=strlen(str);
int p,q;
int flag=1;
int j=0;
for(j=0;j<str_len-1;j++)
{
cout<<"input state"<<endl;
for(int i=0;i<state;i++)
{
if(st[i]==ststate)
{
p=i;
cout<<p<<endl;
break;
}
else
{
p=-1;
}
}
cout<<"input string"<<endl;
for(int i=0;i<state;i++)
{
if(sy[i]==str[j])
{
q=i;
// cout<<q<<endl;
break;
}
else
{
q=-1;
}
}
if(p!=-1 && q!=-1)
{
cout<<"table output :: "<<table[p][q]<<endl;
ststate=table[p][q];
}
}
cout<<endl;
cout<<"----------------------------------------------------------------------------------";
if((table[p][q]==fnstate) && (j==str_len-1))
{
cout<<"String is recognized"<<endl;
flag=0;
}
if(flag!=0)
{
cout<<"String is not recognized.";
}
cout<<endl;
return 0;
}
This part of the code:
while(string[i]!='\0')
{
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
{
uses and changes i in both loops. You need to use something else in one of them.
Ok so I got this thing going here.
I keep getting a few errors.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
//functions called
int get_lmt();
int get_total_trash();
void print_output(int, int);
//why is it void?
int main(void)
{
char hauler[100];
int t_trash=0, lmt=0;
printf("Hello \n What is your name: ");
fflush(stdin);
scanf("%s", &hauler);
t_trash = get_total_trash();
lmt = get_lmt();
printf("Name: %s\n", &hauler);
print_output(lmt, t_trash);
system("pause");
return 0;
}
int get_total_trash()
{
char yn = 'y';
int t_trash = 0, trash=0;
while (yn != 'n')
{
printf("What is your trash: ");
fflush(stdin);
scanf("%i", &trash);
t_trash = trash + t_trash;
printf("Do you have more trash tons? (y or n): ");
fflush(stdin);
scanf("%c", &yn);
}
return t_trash;
}
int get_lmt()
{
int lmt = 0;
printf("What was last months trash: ");
fflush(stdin);
scanf("%i", &lmt);
return lmt;
}
void print_output(int lmt, int t_trash)
{
float rate = 350.00, charge;
int sum=0, total=0;
if (lmt > t_trash)
{
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
else
{
printf("What is your tonnage rate: ");
fflush(stdin);
scanf("%.2f\n", &charge);
sum = t_trash - lmt;
total = sum * charge;
rate = rate + total;
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
}
Now what it should be doing is, The main should be calling the functions on screen as needed.
Now i did all of this with cout cin and it works fine no problems. But when I run this (this is modified to the printf and scanf) it says:
OK UPDATE: Got a ton of it to work. Just one more thing and I should be good. The outcome will not go as expected.
Instead of an output of
last months trash: 100 (asked at the end of the loop)
trash tonnage: 50 (accumulated in the loop)
rate: 350.00 (float variable)
(this is if last month trash was > this month.)
I get just bad numbers all around. It makes no mathematical sense.
Other then that it works fine.
Does the code the the last function look wrong to you guys?
Lots of problems with this code. Lots of them.
1) print_output defintiion takes in a char[100] (char*), print_output declatation takes a char
2) When you pass hauler into print_output, you are passing in hauler[100] (a char, and one pass the end of the array to boot)
3) printf("Name: %s\n", &hauler); hauler is of type char[100] (char*), so &hauler is char**.
there is probably more.
#include <stdio.h>
struct member {
char name[20];
int age;
char sex;
int height;
};
int main(void)
{
int i,j;
struct member input[5]={0,};
int tot, rank, max=0;
int max2[5]={0,};
float res;
for (i=0; i<5; i++)
{
scanf("%s ", input[i].name);
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height);
getchar();
}
scanf("%d", &rank);
max =input[0].height;
for(i=1;i<=5;i++) {
for(j=0;j<5;j++) {
if(max>=input[j].height)
max=max;
else
max=input[j].height;
}
max2[i]=max;
for(j=0;j<5;j++) {
if(max==input[j].height)
input[j].height*=(-1);
}
max=-1;
}
for (i=0; i<5; i++)
{
if(max2[rank]== input[i].height)
printf("%s %d %c %d\n",input[i].name, input[i].age, input[i].sex,input[i].height);
}
fflush(stdin);
getchar();
return 0;
}
The result printed of above my code is nothing...Even the height inputted becomes negative number..
What's wrong with this program?
Input & Print should be the same like example image.......
please help!
The first scanf should be fixed
scanf("%s ", input[i].name);
In the second scanf, the input[i].sex is a char type so you have to use "%c" instead of %s
scanf("%d %s %d", &input[i].age, &input[i].sex, &input[i].height);
should be
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height);
You have a lot of problems here:
1) You're taking the wrong parameters from scanf():
scanf("%s ", input[i].name); // You don't need a & for a string
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height); // you need %c for a
// character
2) You're using for(i=1;i<=5;i++) to access an array of 5 elements, by doing this you're overflowing the array (it should be 0 to 4, not 1 to 5)
3) This is a nit-pick but:
if(max>=input[j].height)
max=max;
that is totally pointless. You don't need to set a variable to itself, just invert the logic (<) and only do the else case.
4) You set all the input[x].height's to the negative of the value they're originally set to here:
input[j].height*=(-1);
Then you check to see if that is the same as the original values which you stored in max2[] before printing here:
if(max2[rank]== input[i].height)
printf("%s %d %s %d\n",input[i].name, input[i].age, input[i].sex,input[i].height);
Well, that's never going to happen, so you'll never print anything
5) fflush(stdin); is not a well defined operation on most systems and could lead to undefined behavior, so don't do it.