I am trying to code for a tic- tac - toe game - c

I am trying to create a function to enter x and o in my board which has counters to 1 - 9 already. Can someone explain me the algorithm and logic so i can try and code accordingly
If someone can guide me through, i am going through different examples but nothing specifically for shorter functions
//function to initialize board and my main and last is the function with printf commands
#include <stdio.h>
#define MAX 3
void InitializeBoard(int m, int n , char board[][n]){
int c =1;
for(int i =0; i<m; i++){
for(int j=0; j< n; j++){
board[i][j] = c+'0';
c++;
}
}
return;
}
void PrintBoard(int m, int n, char board[][n]){
printf("\n %c | %c | %c \n", board[0][0],
board[0][1], board[0][2]);
printf("\n--------------\n");
printf("\n %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\n--------------\n");
printf("\n %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);
return;
}
int main() {
printf("Let's begin the game ! \n " );
char choice;
int m , n ;
char board [MAX][MAX] ;
do {
printf("Press 'p' to print the tic-tac-toe board.\n");
printf("Press 'c' to create the tic-tac-toe board with some X and O celss.\n");
printf("Press 't' to test is the tic-tac-toe board is valid or invalid.\n");
printf("Press 'w' to predict winning cell for the player X and O.\n\n");
printf("Press 'e' to exit\n");
scanf(" %c", &choice);
switch(choice){
case 'p' :
InitializeBoard(m,n,board);
PrintBoard(m,n, board);
break;
case 'c' :
default:
choice =-1;
}
}while(choice!=-1);
return 0;
}
I expect output
1|2|3
-----
4|5|6
-----
7|8|9

The problem is uninitialized variables which you are using to fill the board.
int m , n ;
......
InitializeBoard(m,n,board);
PrintBoard(m,n, board);
You need to initialize them to number of rows and columns.
int m = MAX , n = MAX;

Related

binary tree for sorting and search on c program

So i have a program to data the users input.
in this program i want to make some function
to ask the user for the product coming in
to display the history of data coming in by sorting by date.
to ask the user for the product coming out
to display the history of data coming out by sorting by date.
to search a specific product data by calling the code
to display all the data, the data is sorted by date and then the weight is data coming in minus data coming out
actually i have made a complete program of this, but the teacher updated the assignment. in the previous assignment i mostly use array instead of pointer and for sorting i use recursive bubble sort.
For now i need someone's help to make a sort by date using binary tree and search by product code using binary tree
Note : i must use binary tree because that's the assignment my teacher gave me
assignments are :
have a function with address argument
have a function with array argument
have function with argument as address to a structure
have a function with structure argument
add node to linked list/stack/queue/tree
read/delete node from linked list/stack/queue/tree.
Honestly i still understand linked list/stack/queue/tree. i thought to make a linked list i just change my array to a pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct {
int kode;
int amount;
char variety[20];
int weight;
int date;
}data;
data *innData;
data *outtData;
int menu;
int i;
int pointIn = 0, pointOut=0;
int amount = 0;
char variety[5][20] = {"Fish", "Crab", "Squid", "Clam", "Lobster"};
void sortDate(data *list, int range);
void back_menu();
void input();
void inputHistory();
void output();
void outHistory();
//void sort
//void calculateWeight
//void search();
//void showAll();
int main(){
innData=(data *)malloc(100*sizeof(data));
outtData=(data *)malloc(100*sizeof(data));
do {
printf(" ---------------- MARINE PRODUCT STOCK PROGRAM ---------------");
printf( " \n\nMAIN MENU :\n");
printf( "___________________________________________________________________\n\n");
printf( " 1. Input Product\n\n"); //data that the user input
printf( " 2. Entered History\n\n"); //show the history of the entered data by sorting the date
printf( " 3. Output Product\n\n"); //data that the user take out
printf( " 4. Exited Product\n\n");//show the history of the exited data by sorting the date
printf( " 5. Search Product\n\n"); //show the specific product by calling the code of the product
printf( " 6. Show All Product\n\n");
printf( " _____________________________\n\n");
printf( " choose (1 - 6) : ");
scanf ("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("Please select the number between 1-2\n");
back_menu();
}
switch(menu) {
case 1:
input();
break;
case 2:
inputHistory();
break;
case 3:
output();
break;
case 4:
outHistory();
break;
// case 5:
// search(); // this function is used to search specific product by entering the code
// break;
// case 6:
// showAll(); // this function is used to show all of the stock in the warehouse. but the weight = input-output
// break;
}
free(innData);
free(outtData);
}
while (menu != 6);
system("cls");
printf ("============ Thankyou for using our program ============");
return 0;
}
void input(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (innData+pointIn)->variety, variety[code]);
(innData+pointIn)->kode = code;
printf("\tvariety\t\t : %s\n", (innData+pointIn)->variety);
printf("\t Weight\t : "); scanf(" %d", &(innData+pointIn)->weight );
printf("\t Date (YYYYMMDD)\t : ");scanf(" %d", &(innData+pointIn)->date);
pointIn++;
}
}
back_menu();
}
void inputHistory(){
system("cls");
printf("***** INPUT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (innData+i)->date,(innData+i)->kode, (innData+i)->variety,(innData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void output(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointOut + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (outtData+pointOut)->variety, variety[code]);
(outtData+pointOut)->kode = code;
printf("\tvariety\t\t : %s\n", (outtData+pointOut)->variety);
printf("\tWeight\t : "); scanf(" %d", &(outtData+pointOut)->weight );
printf("\tDate (YYYYMMDD)\t : ");scanf(" %d", &(outtData+pointOut)->date);
pointOut++;
}
}
back_menu();
}
void outHistory(){
system("cls");
printf("***** EXIT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (outtData+i)->date,(outtData+i)->kode, (outtData+i)->variety,(outtData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void back_menu(){
printf("\n\n\t\t\tPress any key to continue.....");
getch();
system("cls");
}

New Data is Replacing Older Data Instead Adding New Data in C

I am making simple C program. This program should be able to store data in memory (not using database). But when i tested it, it can not store more than 1 data. Every time i store new data, the old one get replaced. I hope these screenshot could help you understand what i mean.
As you can see, i input first set of data. It shows up with no problem.
Then, i added second set of data. Where is the first data ? The No 2 Data supposed to be after the No 1 data. But the first data get lost at all.
This is my input code :
//this is function for the input
void masukan() {
n=n+1; //use n as index for the struct (mhsw)
printf("\n");
printf("Masukkan NIM : "); scanf("%s", mhsw[n].nim);
printf("Masukkan Nama : "); scanf("%s", mhsw[n].nama);
printf("Masukkan Golongan UKT : "); scanf("%d", &mhsw[n].golUKT);
mhsw[n].nominalUKT = nominal(mhsw[n].golUKT)*100000;
printf("");
}
//the nominal UKT = factorial of golUKT
int nominal(int n) {
int hasil = 0;
if (n == 1) return 15;
else {
hasil = ((n*n) + nominal(n-1));
return hasil;
}
}
This is my output code :
//this is for the output
void tampil() {
if (!kbhit()) {
printf("\n");
printf(" ===========================================================================\n");
printf(" DATA MAHASISWA \n");
printf("|====|================|====================|==============|=================|\n");
printf("| No | NIM | Nama | Golongan UKT | Nominal UKT |\n");
printf("|====|================|====================|==============|=================|\n");
for(i=0; i<n; i++); //to display record
{
printf("%5d", i);
printf("%17s", mhsw[i].nim);
printf("%20s", mhsw[i].nama);
printf("%15d", mhsw[i].golUKT);
printf("%18d", mhsw[i].nominalUKT);
printf("\n");
}
printf("|====|================|====================|==============|=================|\n");
printf("\n \nPencet sembarang tombol untuk kembali ke Home");
getch();
} else {
menu();
}
}
This is the whole code :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <windows.h>
//global variable
struct mahasiswa
{
char nim[10];
char nama[50];
int golUKT;
long int nominalUKT;
};
struct mahasiswa mhsw[50];
int i, n, nim;
bool ada = false;
char carinim[10];
//prototype
void login();
void menu();
void gotoxY(int, int);
void loading();
void masukan();
int nominal(int);
void tampil();
void cari();
//main function
void main() {
login();
}
void login() {
char user[10], pass[10];
int x, y;
printf("Masukkan Username : "); scanf("%s", user);
printf("Masukkan Password : "); scanf("%s", pass);
x = strcmp(user, "admin");
y = strcmp(pass, "admin123");
if (x == 0 && y == 0) {
menu();
}
else {
system("cls");
printf("Gagal Login, Ulangi Proses\n");
login();
}
}
void menu()
{
int pilih;
system("cls");
printf(" ____________________________________________________\n");
printf("| Siukat Lite |\n");
printf("|____________________________________________________|\n");
printf("|_______________________Home_________________________|\n");
printf("| 1. Pendaftaran Mahasiswa |\n");
printf("| 2. Daftar Golongan UKT |\n");
printf("| 3. Cari NIM |\n");
printf("| 4. Cetak Data Siukat |\n");
printf("| Ketik sembarang nomor untuk keluar |\n");
printf("|____________________________________________________|\n");
printf("Masukkan Pilihan Nomor : ");
scanf("%d",&pilih);
switch(pilih)
{
case 1:
//loading();
printf("\nPendaftaran Mahasiswa");
masukan();
menu();
break;
case 2:
case 3:
printf("Cari NIM");
cari();
break;
case 4:
//loading();
printf("\nData Siukat");
tampil();
default:
menu();
}
}
void gotoxy (int x,int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
dwCursorPosition.X = x;
dwCursorPosition.Y = y;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition);
}
void loading() {
int a;
char x;
gotoxy(1,12);
for(a=0;a<=5;a++)
{
usleep(500000);
printf("*",x);
}
}
//for input record
void masukan() {
printf("\n");
printf("Masukkan NIM : "); scanf("%9s", mhsw[n].nim);
printf("Masukkan Nama : "); scanf("%49s", mhsw[n].nama);
printf("Masukkan Golongan UKT : "); scanf("%d", &mhsw[n].golUKT);
mhsw[n].nominalUKT = nominal(mhsw[n].golUKT)*100000;
printf("");
n=n+1;
}
int nominal(int n) {
int hasil = 0;
if (n == 1) return 15;
else {
hasil = ((n*n) + nominal(n-1));
return hasil;
}
}
//for find NIM
void cari() {
printf("\nMasukkan NIM :"); scanf("%s", carinim);
printf("\n");
if (!kbhit()) {
for(i=0; i<n; i++) {
if (strcmp(carinim, mhsw[i].nim) == 1) {
ada = true;
} else {
ada = false;
}
}
if(ada) {
printf("NIM : %s \n", mhsw[i].nim);
} else {
printf("Data Tidak Ditemukan");
}
} else {
menu();
}
}
//for showing the record
void tampil() {
if (!kbhit()) {
printf("\n");
printf(" ===========================================================================\n");
printf(" DATA MAHASISWA \n");
printf("|====|================|====================|==============|=================|\n");
printf("| No | NIM | Nama | Golongan UKT | Nominal UKT |\n");
printf("|====|================|====================|==============|=================|\n");
for(i=0; i<n; i++);
{
printf("%5d", i);
printf("%17s", mhsw[i].nim);
printf("%20s", mhsw[i].nama);
printf("%15d", mhsw[i].golUKT);
printf("%18d", mhsw[i].nominalUKT);
printf("\n");
}
printf("|====|================|====================|==============|=================|\n");
printf("\n \nPencet sembarang tombol untuk kembali ke Home");
getch();
} else {
menu();
}
}
Thanks for any help
UPDATE : i tried to put increment after the insertion and see the value of n. Still doesn't work. Here is some screenshot.
The value of n before insertion is still 0
The value of n after insertion, it incremented to 1. But the data doesn't get recorded at all.
You have a ; after your for inside tampil().
for(i=0; i<n; i++);
It's causing your loop body to be empty so nothing is printed inside tampil().
To protect against such mistakes use a good compiler gcc and enable all warnings (for gcc it's -Wall -Wextra). Ex. gcc outputs this helpful warning message:
1.c: In function ‘tampil’:
1.c:167:9: warning: this ‘for’ clause does not guard... [-Wmisleading-indentation]
167 | for(i=0; i<n; i++);
| ^~~
1.c:168:9: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘for’
168 | {
| ^
It is due to the fact that you do the n = n+1 instruction before the insertion in masukan(). You must move this instruction at the end of the function.
When the program starts, the value of n is 0. When you insert a new set of values, you first increment n and store thus the values at index 1. The values at index 0 are the default values.
When you print the values, you print the values with index 0 to n-1. This doesn't include the value at index n that you just inserted.
By moving the increment of n at the end of the new value insertion, the first value set will be inserted at index position 0 and n is the number of values in the table. n is also the index of the after last values in the table. This is where you insert the next value after what you increment n.
EDIT: another error is a ; after the for(i=0; i<n; i++) in the tampil function. That is the reason one line is printed regardless of the value of n.

scanf in function seems to be writing garbage values to one array but not the other, despite both being identical

So in the function getRoster, I have two arrays that are defined in the same way in main and called in the same way. But for some reason, one of the scanf functions write garbage data to the array so that in line 91 (A debugging line in this case) one value is the one I entered and the other is seemingly random. I've checked this code top to bottom already to see if there were any notations that I added to one array and not the other, and I can't seem to find a single one.
#include <stdio.h>
#include <stdlib.h>
void getRoster(int *jerseyNumbers[10], int *playerRatings[10])
{
int i;
for (i=0; i<5; ++i)
{
printf("Enter player %d's jersey number\n", i+1);
scanf("%d", &jerseyNumbers[i]);
printf("Enter player %d's rating\n", i+1);
scanf("%d", &playerRatings[i]);
}
}
void updateRating(int *jerseyNumbers[10], int *playerRatings[10])
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i)
if(jerseyNumbers[i]==n)
hold = n;
if (n=-1);
printf("Error");
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
void aboveRating()
{
}
void replacePlayer()
{
}
void outputRoster(int *jerseyNumbers[10], int *playerRatings[10])
{
int i;
for (i=0; i<5; ++i)
{
printf("Player %d -- Jersey number: %d , Rating: %d \n", i+1, jerseyNumbers[i], playerRatings[i]);
}
}
void menu(int *jerseyNumbers[10], int *playerRatings[10])
{
char menuInput;
printf("\nMENU\n");
printf("u - Update player rating\n");
printf("a - Output players above a rating\n");
printf("r - Replace player\n");
printf("o - Output roster\n");
printf("q - Quit\n");
printf("\nChoose an option:\n");
scanf(" %c", &menuInput);
if (menuInput == 'u')
{updateRating(&jerseyNumbers[10], &playerRatings[10]);
}
else if (menuInput == 'a')
{aboveRating();
}
else if (menuInput == 'r')
{replacePlayer();
}
else if (menuInput == 'o')
{outputRoster(&jerseyNumbers[10], &playerRatings[10]);
}
else if (menuInput == 'q')
printf("Reached Quit");
else
printf("Input Error\n");
}
int main()
{
int *jerseyNumbers[10];
int *playerRatings[10];
char menuInput;
int quitFlag = 0;
getRoster(&jerseyNumbers[10], &playerRatings[10]);
printf("%d %d", jerseyNumbers[0], playerRatings[1]);
menu(&jerseyNumbers[10], &playerRatings[10]);
return 0;
}
Refer to #NaveenKumar and #DeiDei's comment to your question.
Actually, the logic of your program is alright. But where you've gone wrong is the syntax regarding how you have declared the arrays and passed them as arguments to the functions. I have listed the changes to be made below:
First of all Dylan, do not declare an array as: int
*jerseyNumbers[10] and int *playerRatings[10]. For the regular array which you actually need, just declare as:
a. *jerseyNumbers and *playerRatings... Remove the size. OR
b. jerseyNumbers[10] and playerRatings[10]... Remove the * from the declaration.
When you're passing these arrays as arguments to a function, don't ever send it how you've done. Just pass the array name as an argument. Like this: getRoster(jerseyNumbers, playerRatings); and menu(jerseyNumbers, playerRatings);.
In the function definition, the parameters representing the array should be either *arrayname or arrayname[size]. Since we have used the first during declaration, use the same here as follows:
void getRoster(int *jerseyNumbers, int *playerRatings) {...},
void updateRating(int *jerseyNumbers, int *playerRatings){...},
void outputRoster(int *jerseyNumbers, int *playerRatings) {...},
void menu(int *jerseyNumbers, int *playerRatings) {...}.
And as #PaulSm4 has suggested don't use the semi-colon at the end of an if conditional. Though this isn't the cause of your problem here, it is a practice you need to follow and mistake to be avoided.
I have attached the working code below, along with the output.
CODE:
#include <stdio.h>
#include <stdlib.h>
void getRoster(int *jerseyNumbers, int *playerRatings)
{
int i;
for (i=0; i<5; ++i)
{
printf("Enter player %d's jersey number\n", i+1);
scanf("%d", &jerseyNumbers[i]);
printf("Enter player %d's rating\n", i+1);
scanf("%d", &playerRatings[i]);
}
}
void updateRating(int *jerseyNumbers, int *playerRatings)
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i)
if(jerseyNumbers[i]==n)
hold = n;
if (n=-1)
printf("Error");
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
void aboveRating()
{
}
void replacePlayer()
{
}
void outputRoster(int *jerseyNumbers, int *playerRatings)
{
int i;
for (i=0; i<5; ++i)
{
printf("Player %d -- Jersey number: %d , Rating: %d \n", i+1, jerseyNumbers[i], playerRatings[i]);
}
}
void menu(int *jerseyNumbers, int *playerRatings)
{
char menuInput;
printf("\nMENU\n");
printf("u - Update player rating\n");
printf("a - Output players above a rating\n");
printf("r - Replace player\n");
printf("o - Output roster\n");
printf("q - Quit\n");
printf("\nChoose an option:\n");
scanf(" %c", &menuInput);
if (menuInput == 'u')
{updateRating(jerseyNumbers, playerRatings);
}
else if (menuInput == 'a')
{aboveRating();
}
else if (menuInput == 'r')
{replacePlayer();
}
else if (menuInput == 'o')
{outputRoster(jerseyNumbers, playerRatings);
}
else if (menuInput == 'q')
printf("Reached Quit");
else
printf("Input Error\n");
}
int main()
{
int jerseyNumbers[10];
int playerRatings[10];
char menuInput;
int quitFlag = 0;
getRoster(jerseyNumbers, playerRatings);
printf("%d %d", jerseyNumbers[0], playerRatings[1]);
menu(jerseyNumbers, playerRatings);
return 0;
}
OUTPUT:
Enter player 1's jersey number
1
Enter player 1's rating
10
Enter player 2's jersey number
2
Enter player 2's rating
20
Enter player 3's jersey number
3
Enter player 3's rating
30
Enter player 4's jersey number
4
Enter player 4's rating
40
Enter player 5's jersey number
5
Enter player 5's rating
50
1 20
MENU
u - Update player rating
a - Output players above a rating
r - Replace player
o - Output roster
q - Quit
Choose an option: o
Player 1 -- Jersey number: 1 , Rating: 10
Player 2 -- Jersey number: 2 , Rating: 20
Player 3 -- Jersey number: 3 , Rating: 30
Player 4 -- Jersey number: 4 , Rating: 40
Player 5 -- Jersey number: 5 , Rating: 50
Hope this helps.
STRONG SUGGESTION:
Get in the habit of using curly braces often - even when you don't need them.
void updateRating(int *jerseyNumbers, int *playerRatings)
// You probably only need a pointer or an array - but probably not both ;)
{
int i, n = -1, hold;
printf("Enter a jersey number:\n");
scanf("%d", n);
for (i=0; i<5; ++i) { // Curly brace here...
if(jerseyNumbers[i]==n) { // And here...
hold = n;
}
}
if (n=-1) { // BUG ALERT: deleted ";" (and added a brace)
printf("Error"); // BUG ALERT: fixed this by removing ";"?
} else {
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
Or perhaps better:
void updateRating(int *jerseyNumbers, int *playerRatings)
{
int n;
printf("Enter a jersey number:\n");
scanf("%d", n);
printf("Enter a new rating for player:\n");
scanf("%d", &playerRatings[n]);
}
And, as Rishikesh Raje correctly pointed out:
The definition of the array's and the function calls for OP is also
not correct. Please mention this also.

invalid conversion from 'char*' to 'char' [-fpermissive]

i want to make cashier program by C language. i using structure for record but the problem is when i try to display the receipt of payment by defined name of item detail[i].name and price detail.[i].price for looping, i got this message
[Error] invalid conversion from 'char*' to 'char' [-fpermissive]
this is my script
#include<stdio.h>
#include <stdlib.h>
struct item{
char name[10];
int price;
int barcode;
};
struct item detail[10]={
"item1",10,1,
"item2",20,2,
"item3",30,3,
"item4",40,4,
"item1",50,5,
"item2",60,6,
"item3",70,7,
"item4",80,8,
"item3",90,9,
"item4",100,10
};
int main(){
int ibarcode[10];int qty[10];char b[10];int price[10];int ju[10];int tot[10];
int j,i,k,grand;
char a;
printf("Cashier program\n");
for(j=0;j<10;j++){
printf("enter barcode : ");scanf("%d",&ibarcode[j]);
for(i=0;i<10;i++){
if(ibarcode[j]==detail[i].barcode){
printf("item name: %s\n",detail[i].name);
printf("price : %d\n",detail[i].price);
printf("Quantity : ");scanf("%d",&qty[j]);
tot[j]=detail[j].price*qty[j];
}
if(ibarcode[j] > 10){
printf("Barcode not valid\n");
j--;
break;
}
}
printf("\nDo you want to buy again? [Y/N] = ");scanf("%s", &a);
b[j] = detail[i].name;
ju[j] = detail[i].price;
if(a=='Y'||a=='y'){
continue;
} else {
break;
}
}
grand = 0; system("cls");
printf("\n name Kasir = Addzifi Moch G\n");
printf(" Tanggal = 03 januari 2017\n");
printf(" Jam = 14:05 WIB\n\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("| Barcode | name item\t\t\t| price \t\t| Quantity\t| Total |\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
for(k=0; k<=j; k++){
grand += tot[k];
printf("| %d \t | %s\t | %d\t\t | %d\t\t\t| %d |\n", ibarcode[k], b[k], ju[k], qty[k], tot[k]);
}
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("|\t\t\t\t\t\t\t Total Yang Harus Dibayarkan = %d |\n", grand);
printf("+-------------------------------------------------------------------------------------------------+\n");
}
I bet that happens on the line
b[j] = detail[i].name;
and that is because b is an array of characters and name is a string, so you want to assign to b[j], a char, a string.
use strcpy:
strcpy(b, detail[i].name);

looping a program that converts to uppercase and shifts 4 letter grades in C

This program calls two functions uppercase(), which converts the input to uppercase, and shift(), which shifts the grade input.
Here's my uppercase() function:
void uppercase(char *p)
{
if(islower(*p)) {
*p = toupper(*p);
}
}
Here's the shift() function:
void shift(char *p1, char *p2, char *p3, char *p4)
{
int count = 0;
do {
++count;
char tmp;
tmp = *p4;
*p4 = *p3;
*p3 = *p2;
*p2 = *p1;
*p1 = tmp;
printf("Grades Shifted #%i: %c %c %c %c \n", count, *p1, *p2, *p3, *p4);
} while (count < 4);
}
Here's my main function.
#include <stdio.h>
#include <ctype.h>
main (void)
{
float choice;
do {
char c1, c2, c3, c4;
printf ("Enter 4 letter grades to find statistics: ");
scanf("%c %c %c %c", &c1, &c2, &c3, &c4);
getchar();
uppercase(&c1);
uppercase(&c2);
uppercase(&c3);
uppercase(&c4);
printf("Input Grades: %c %c %c %c\n", c1, c2, c3, c4);
shift(&c1, &c2, &c3, &c4);
printf("Want to shift more grades (y/n)? ");
choice = getchar();
} while ( choice == 'y' || choice == 'Y');
getchar();
}
My output looks like this
Enter 4 letter grades to find statistics: abcd
Input Grades: A B C D
Grades Shifted #1: D A B C
Grades Shifted #2: C D A B
Grades Shifted #3: B C D A
Grades Shifted #4: A B C D
Want to shift more grades (y/n)? y
Enter 4 letter grades to find statistics: adff
Input Grades:
A D F
Grades Shifted #1: F
A D
Grades Shifted #2: D F
A
Grades Shifted #3: A D F
Grades Shifted #4:
A D F
Want to shift more grades (y/n)?
The format gets messed up on the second input, and when I input another y after the second input, the program closes. I've been tinkering with this for the past hour and I can't figure out why my formatting gets messed up or why the loop closes/crashes on the third attempt.
Also how can I make it so that my main function only accepts inputs of A-D or F.
Thanks.
I think it's because you have a new line sitting in your getchar() input
When you enter 'y' then press enter, you're getting "y\n".
Clear the input when re-entering the do while loop
printf("Want to shift more grades (y/n)? ");
choice = getchar();
c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
} while ( choice == 'y' || choice == 'Y');
For your second question:
You need to check the values of c1,c2,c3,c4 luckily there's a function for that
while( !(isalpha(c1) && isalpha(c2) && isalpha(c3) && isalpha(c4)) )
printf ("Enter 4 letter grades to find statistics: ");
scanf("%c %c %c %c", &c1, &c2, &c3, &c4);
getchar();
Note that the isalpha function simply checks the value of each character... here's an ascii table, notice where A-Z and a-z are. http://www.asciitable.com/
scanf/getchar() line clearing: http://www.velocityreviews.com/forums/t318260-peek-at-stdin-flush-stdin.html
you can use scanf() instead of getchar() as scanf will stop until it reaches a whitespace

Resources