abort trap: 6 error while running this program in C - c

I am writing this code that takes a calculation from a file on the command line, then calculates it. I have gotten to a point where I am able to get each part of the file into a string array, however when I try to run that array into a method to calculate it, I get an abort trap: 6 error during run time. I am writing in c using emacs and the cc in the terminal to compile.
I am running this in main when it gives the error, with these variables initialized:
char items[10][10];
int sig;
int numOfItems = n-1;
double result[3];
sig=calculate(items, numOfItems, result);
The method is the following, I know it does not fully work yet, but it seems to not even enter the method because it does not print out the test print statements I have put:
int calculate(char items[10][10], int numOfItems, double *res){
printf("test2");
int flag, i, c, j, numdigits, decindicate, operatorindicate,n,m;
double ans;
double numbers[30];
char operators[30];
for(n=0; n<30; n++){
numbers[n]=0;
}
flag=1;
i=0;
numdigits=0;
decindicate=0;
operatorindicate=0;
n=0;
m=0;
j=0;
while(n<numOfItems){
c=items[n][0];
if(('0'<=c) && (c<='9')){
m=0;
while(c!='\0'){
c=items[n][m];
if(('0'<=c) && (c<='9')){
numbers[i] = numbers[i]*10+(c-'0');
}else if(c=='.'){
decindicate=1;
m++;
break;
}else{
flag=0;
break;
}while(decindicate>0){
c=items[n][m];
if(('0'<=c) && (c<='9')){
numbers[i]=numbers[i]+((c-'0')/(10^decindicate));
decindicate++;
}else{
flag=0;
break;
}m++;
}
i++;
}
}else if(c=='+' || c=='-' || c=='*' || c=='/'){
operators[j]=c;
j++;
}else{
flag=0;
break;
}n++;
}
for(i=0; i<numdigits; i++){
printf("%lf \n",numbers[i]);
}for(i=0; i<m; i++){
printf("char %c \n", operators[i]);
}
ans=numbers[0];
for(i=0; i<n-1; i++){
if(operators[i]=='+'){
ans=ans+numbers[i+1];
}else if(operators[i]=='-'){
ans=ans-numbers[i+1];
}else if(operators[i]=='*'){
ans=ans*numbers[i+1];
}else if(operators[i]=='/'){
ans=ans/numbers[i+1];
}
}
*res=ans;
return flag;
}
Here is the entire code if it's something out of these bounds that I don't even realize:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int calculate(char items[10][10], int numOfItems, double *res){
int flag, i, c, j, numdigits, decindicate, operatorindicate,n,m;
double ans;
double numbers[30];
char operators[30];
for(n=0; n<30; n++){
numbers[n]=0;
}
flag=1;
i=0;
numdigits=0;
decindicate=0;
operatorindicate=0;
n=0;
m=0;
j=0;
while(n<numOfItems){
c=items[n][0];
if(('0'<=c) && (c<='9')){
m=0;
while(c!='\0'){
c=items[n][m];
if(('0'<=c) && (c<='9')){
numbers[i] = numbers[i]*10+(c-'0');
}else if(c=='.'){
decindicate=1;
m++;
break;
}else{
flag=0;
break;
}while(decindicate>0){
c=items[n][m];
if(('0'<=c) && (c<='9')){
numbers[i]=numbers[i]+((c-'0')/(10^decindicate));
decindicate++;
}else{
flag=0;
break;
}m++;
}
i++;
}
}else if(c=='+' || c=='-' || c=='*' || c=='/'){
operators[j]=c;
j++;
}else{
flag=0;
break;
}n++;
}
for(i=0; i<numdigits; i++){
printf("%lf \n",numbers[i]);
}for(i=0; i<m; i++){
printf("char %c \n", operators[i]);
}
ans=numbers[0];
for(i=0; i<n-1; i++){
if(operators[i]=='+'){
ans=ans+numbers[i+1];
}else if(operators[i]=='-'){
ans=ans-numbers[i+1];
}else if(operators[i]=='*'){
ans=ans*numbers[i+1];
}else if(operators[i]=='/'){
ans=ans/numbers[i+1];
}
}
*res=ans;
return flag;
}
int main(int argc, char **argv){
int n, m, i;
char digits[50]; //used to store digits before adding necessary spaces
char items[10][10]; //will store string array of items in equation
FILE *fp, *fp2;
int sig; //will indicate if there is an invalid character
double result[3] = {0}; //will return result of equation
fp = fopen(argv[1], "r");
if(fp==NULL){
printf("Please provide file");
}
fp2 = fopen("temp", "w+"); //will read to file temp
n=0;
while(0==0){
digits[n]=fgetc(fp);
if(digits[n]==EOF){
digits[n]='\0';
break;
}
n++;
}
n=0;
char temp1;
char temp2;
while(digits[n]!='\0'){
if((('0'<=digits[n]) && (digits[n]<='9') && (digits[n+1]=='+' || digits[n+1]=='-' || digits[n+1]=='*' || digits[n+1]=='/')) || ((digits[n]=='+' || digits[n]=='-' || digits[n]=='*' || digits[n]=='/') && (('0'<=digits[n+1]) && (digits[n+1]<='9')))){
temp1=digits[n+1];
digits[n+1]=' ';
m=n+2;
while(digits[m-1]!='\0'){
temp2=temp1;
temp1=digits[m];
digits[m]=temp2;
m++;
}
}
fputc(digits[n], fp2);
n++;
}
//test if digit array fills correctly
n=0;
while(digits[n]!='\0'){
printf("testings digits array: %c \n", digits[n]);
n++;
}
//scans the temp file to form string array
rewind(fp2);
i=1;
n=0;
while(i==1){
i=fscanf(fp2, "%s", items[n]);
n++;
}
int numOfItems = n-1;
//test if char array items fills correctly
n=0;
while(n<numOfItems){
printf("testing items array: %s \n", items[n]);
n++;
}
sig=calculate(items, numOfItems, result);
if (sig==0){
printf("This is not a valid operation. \n");
}else {
printf("The calculation equals %lf \n", result[0]);
}
remove("temp");
}
the file I am using to test is sc1 which contains the following:
34 + 96 - 10 / 2
This is what the whole program prints out when using this sc1 file:
testings digits array: 3
testings digits array: 4
testings digits array:
testings digits array: +
testings digits array:
testings digits array: 9
testings digits array: 6
testings digits array:
testings digits array: -
testings digits array:
testings digits array: 1
testings digits array: 0
testings digits array:
testings digits array: /
testings digits array:
testings digits array: 2
testing items array: 34
testing items array: +
testing items array: 96
testing items array: -
testing items array: 10
testing items array: /
testing items array: 2
Abort trap: 6
I feel so lost, if someone could help that would be great.

in calculate the while(c!='\0') was an infinite loop. c=items[n][m]; never got a new value for c as m wasn't incremented unless a dot was detected. i was incremented so each iteration accessed numbers[i] and when i exceeded the boundary of numbers[30] it failed.
numbers[i]=numbers[i]+((c-'0')/(10^decindicate)); is another problem as ^ is bit XOR. Not what you want here to raise the power of 10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int calculate(char items[10][10], int numOfItems, double *res){
int flag = 1, i = 0, c, ops = 0, decindicate = 0, nums = 0,item = 0,each = 0;
double ans;
double numbers[30] = { 0.0};
char operators[30];
printf ( "calculating\n");
while ( item < numOfItems) {
c = items[item][0];
if ( ( '0' <= c && c <= '9') || c == '.') {
each = 0;
decindicate = 0;
while ( '\0' != ( c = items[item][each])) {
if ( ( '0' <= c) && ( c <= '9')) {
numbers[nums] = numbers[nums] * 10 + ( c - '0');
if ( decindicate) {
decindicate++;
}
}
else if ( c == '.') {//found a dot
decindicate = 1;//set to 1
each++;
continue;
} else {
flag = 0;
break;
}
each++;//advance each character
}
while ( decindicate > 1) {
decindicate--;
numbers[nums] /= 10;//divide by power of 10 digits after dot
}
nums++;//advance nums
if ( nums >= 30) {
printf ( "too many numbers\n");
return 0;
}
} else if ( c == '+' || c == '-' || c == '*' || c == '/') {
operators[ops] = c;
ops++;//sdvance ops
if ( ops >= 30) {
printf ( "too many operators\n");
return 0;
}
} else {
flag = 0;
break;
}
item++;//advance item
}
for ( i = 0; i < nums; i++) {
printf ( "numbers %f \n", numbers[i]);
}
for ( i = 0; i < ops; i++) {
printf ( "operators %c \n", operators[i]);
}
ans = numbers[0];
for ( i = 0; i < item - 1; i++) {
switch ( operators[i]) {
case '+':
ans = ans + numbers[i + 1];
break;
case '-':
ans = ans - numbers[i + 1];
break;
case '*':
ans = ans * numbers[i + 1];
break;
case '/':
ans = ans / numbers[i + 1];
break;
}
}
*res = ans;
return flag;
}
int main ( int argc, char **argv) {
int n = 0, i, digit = 0;
char digits[50] = ""; //used to store digits before adding necessary spaces
char items[10][10] = { { ""}}; //will store string array of items in equation
FILE *fp = NULL, *fp2 = NULL;
int sig = 0; //will indicate if there is an invalid character
int space = 1;//skip leading whitespace
int operator = 1;//must have a number first
int number = 0;
int dot = 0;
double result = 0.0f; //will return result of equation
if ( NULL == ( fp = fopen ( argv[1], "r"))) {
printf ( "Please provide file\n");
return 0;
}
if ( NULL == ( fp2 = fopen ( "temp", "w+"))) { //will read to file temp
printf ( "could not open temp file\n");
fclose ( fp);
return 0;
}
n = 0;
while ( EOF != ( digit = fgetc ( fp))) {
digits[n] = digit;
n++;
if ( n >= 49) {
break;
}
}
digits[n] = '\0';
fclose ( fp);
n = 0;
while ( digits[n] != '\0') {
switch ( digits[n]) {
case ' ':
case '\t':
case '\n':
if ( space) {
break;
}
space = 1;
//do not reset so as to detect consecutive numbers or operators
//number = 0;
//operator = 0;
dot = 0;
fputc ( digits[n], fp2);
break;
case '.':
if ( dot) {
break;
}
if ( space && number) {
printf ( "bad format. expected operation\n");
return 0;
}
if ( !number) {
fputc ( ' ', fp2);
}
space = 0;
number = 1;
operator = 0;
dot = 1;
fputc ( digits[n], fp2);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if ( space && number) {
printf ( "bad format. expected operation\n");
return 0;
}
if ( !number) {
fputc ( ' ', fp2);
}
space = 0;
number = 1;
operator = 0;
dot = 0;
fputc ( digits[n], fp2);
break;
case '+':
case '-':
case '*':
case '/':
if ( space && operator) {
printf ( "bad format. expected number\n");
return 0;
}
if ( !operator) {
fputc ( ' ', fp2);
}
number = 0;
operator = 1;
dot = 0;
fputc ( digits[n], fp2);
space = 1;
fputc ( ' ', fp2);
break;
}
n++;
}
//scans the temp file to form string array
rewind(fp2);
i = 1;
n = 0;
while ( i == 1) {
i = fscanf ( fp2, "%s", items[n]);
n++;
if ( n >= 10) {
break;
}
}
fclose ( fp2);
int numOfItems = n-1;
//test if char array items fills correctly
n = 0;
while ( n < numOfItems) {
printf ( "testing items array: %s \n", items[n]);
n++;
}
sig = calculate ( items, numOfItems, &result);
if ( sig == 0) {
printf ( "This is not a valid operation. \n");
} else {
printf ( "The calculation equals %lf \n", result);
}
remove ( "temp");
return 0;
}

Related

C language: Given a string, delete/remove the words that contain the n number of vowels

Given an integer n, the program has to delete each word, that contains the n number of vowels.
The string is read from a test.txt file, which contains the following:
Astazi nu este maine.
Currently my program contains a count1 function, that counts the number of characters and vowels for each word in the string.
How can I use the data from count1 function as a refference when typing in the n vowels to delete the needed words then print the updated string?
I have an idea, which I'm unsure how to implement. In count1 we already count the number of vowels per each word, so, given n by the user we check if this number is equal to v in the count1 function and so we do int num_of_words++, then we do a loop, which prints out the needed words, until num_of_words=0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void count1 (char* str)
{
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
default:
continue;
case ' ':
case '\t':
case '\n':
case '\0':
len = i - 1 - w;
printf("'%.*s': %d characters, %d vowels\n", len, str+w, len, v );
if (c)
break;
else
return;
}
break;
}
}
void count2 (char* str, int n)
{
char line2[128];
int ls=strlen(str);
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
default:
continue;
case ' ':
case '\t':
case '\n':
case '\0':
for(int k = 0; str[k] != '\0'; k++)
{
if (k == 0 || isspace(str[k]))
{
if(v==n)
{
strcat(line2, str+1);
}
}
}
printf("%s ", line2);
if (c)
break;
else
return;
}
break;
}
}
int main()
{
FILE *fp;
char line[128];
int c=0, count[26]= {0}, x;
int n;
fp = fopen("test.txt", "r");
fscanf(fp, "%[^\n]", line);
fclose(fp);
printf("%s\n\n", line);
while (line[c] != '\0')
{
if (line[c] >= 'a' && line[c] <= 'z')
{
x = line[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
{
printf("%c occurs %d times.\n", c + 'a', count[c]);
}
printf("\n");
count1(line);
printf("\nInsert n: ");
scanf("%d", &n);
count2(line, n);
return 0;
}
If you have a string str that consists of separate words, separated one from another by ' ' or '\n' or '\t', and you want to have a string that contains all the words in str that satisfy some condition, it will be a bit difficult to program it such that it will be "in-place", i.e. to change str to the desired string, without using a "helper array" of some sort.
Instead, I would recommend to create a new char array with the same size (say str2), and every time you find a word that satisfies the condition (the condition can be for example: doesn't have 1 vowel), you copy the word that you found from str to str2.
Something like this:
char str[128];
// read from file to str using fscanf
char str2[128];
for (int c = 0; str[c] != '\0'; ++c)
{
if (c == 0 || isspace(str[c]))
{
if (! is_1_vowel[str+1]) // if it doesn't have exacly one vowel
{
// copy the word from str to str2
strcat_word(str2, str+1); // a user-defined adapted version of strcat that will copy from src to dest only till src reaches a space character or '\0'
}
}
}
I'm assuming here that is_1_vowel will be a function that goes over a single word (and not the whole line or file), and returns 1 if it satisfies the condition (has 1 vowel), and returns 0 otherwise.
Here's my final solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void count1 (char* str)// count numbers of vowels for each word
{
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
default:
continue;
case ' ':
case '\t':
case '\n':
case '\0':
len = i - 1 - w;
printf("'%.*s': %d characters, %d vowels\n", len, str+w, len, v );
if (c)
break;
else
return;
}
break;
}
}
void print_x(char* str, int n)
{
char* tmp;
unsigned int cnt = 0, stat = 0;
const char aeiou[] = "AEIOUaeiou";
while(*str)
{
switch(stat)
{
case 0://the word did not start
if (!isalpha(*str))
{
putchar(*str);
break;
}
stat = 1;
tmp = str;
cnt = 0;
case 1://the word started
if (strchr(aeiou, *str))
{
cnt++;
break;
}
if (! isalpha(*str))
{
if (cnt != n)
while(tmp <= str) putchar(*(tmp++));
else putchar(*str);
stat = 0;
}
} // end switch
++str;
}
if (stat)
{
--str;
if (cnt != n) while(tmp <= str) putchar(*(tmp++));
}
}
int main()
{
FILE *fp;
char line[128], line2[128];
int c=0, count[26]= {0}, x;
int n,a;
int i,j;
fp = fopen("test.txt", "r");
fscanf(fp, "%[^\n]", line);
fclose(fp);
printf("%s\n\n", line);
while (line[c] != '\0')
{
if (line[c] >= 'a' && line[c] <= 'z')
{
x = line[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
{
printf("%c occurs %d times.\n", c + 'a', count[c]);
}
for (i = 0; i < 26; ++i)
{
for (j = i + 1; j < 26; ++j)
{
if (count[i] < count[j])
{
a = count[i];
count[i] = count[j];
count[j] = a;
}
}
}
printf("\n\n");
for (c = 0; c < 26; c++)
{
printf("%c occurs %d times.\n", c + 'a', count[c]);
}
printf("\n");
count1(line);
printf("\nInsert n: ");
scanf("%d", &n);
if (!(fp = fopen("./test.txt", "r")))
{
printf("unable open file\n");
return 1;
}
while (fgets(line, 128, fp))
print_x(line, n);
fclose(fp);
return 0;
}

Searching an Array of Strings from User Input in C

I've got this homework assignment where we get the user to enter the amount of lines of strings they desire, they then proceed to enter them which gets stored in a 2D Array (thus creating an array of strings). Then a switch case menu will be displayed which should
Search a character entered by the user, returns the amount of times the character occurred in the array
Search a word entered by the user, returns the amount of times the word occurred in the array
Have the user enter a specified word length and return the amount of times words of the specified length occur.
I have a couple problems with my code. The program runs without errors from the compiler. The searchByCharacter function works fine but the searchByWord only returns a value of 0 regardless of any word inputted and nothing happens after I input a number for the searchByLength function. The program freezes after I enter a length once I select the searchByLength function. I've been at this for a while and I don't know where I'm going wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 80
#define MAX_LINES 10
#define WORD_LENGTH 20
void readText(char text[][MAX_LINE_LENGTH], int n)
{
int i;
printf("Enter %d number of lines:\n", n);
for(i = 0; i < n; i++)
{
scanf(" %[^\n]s", text[i]);
}
}
int searchByCharacter(char text[][MAX_LINE_LENGTH], int n, char c)
{
int i, charCount = 0, j = 0;
for(i = 0; i < n; i++)
{
j = 0;
while(text[i][j] != '\0')
{
if(text[i][j] == c)
{
charCount++;
}
j++;
}
}
return charCount;
}
int searchByWord(char text[][MAX_LINE_LENGTH], int n, char * keyword)
{
int i, wordCount = 0;
for(i = 0; i < n; i++)
{
int j = 0;
int lengthOfWord = 0;
char wordCheck[WORD_LENGTH];
char * currentLine = text[i];
while(currentLine[j] != '\0')
{
if (currentLine[j] == ' ' || currentLine[j] == '\n' || currentLine[j] == ',' || currentLine[j] == '.' ||
currentLine[j] == ';')
{
wordCheck[lengthOfWord] = '\0';
int matchingWord = strcmp(wordCheck, keyword);
if(matchingWord == 0)
{
wordCount++;
}
lengthOfWord = 0;
j++;
continue;
}
wordCheck[lengthOfWord] = currentLine[n];
lengthOfWord++;
j++;
}
}
return wordCount;
}
int searchByLength(char text[][MAX_LINE_LENGTH], int n, int wordLen)
{
int i, lengthCount = 0;
for(i = 0; i < n; i++)
{
int lengthOfWord = 0;
int j = 0;
char * currentLine2 = text[i];
while(currentLine2[j] != '\0')
{
if (currentLine2[j] == ' ' || currentLine2[j] == '\n' || currentLine2[j] == ',' || currentLine2[j] == '.' ||
currentLine2[j] == ';')
{
if(lengthOfWord == wordLen)
{
lengthCount++;
}
lengthOfWord = 0;
n++;
continue;
}
lengthOfWord++;
n++;
}
}
return lengthCount;
}
int main(void)
{
char textInput[MAX_LINES][MAX_LINE_LENGTH];
printf("Enter number of lines (<10): ");
int textLines = 0;
scanf("%d", &textLines);
while(textLines < 1 || textLines > 10)
{
printf("Invalid Input.\n");
printf("Enter number of lines (<10): ");
scanf("%d", &textLines);
}
if(textLines >= 1 && textLines <= 10)
{
readText(textInput, textLines);
int menuActive = 1;
while(menuActive)
{
printf("\nText Analysis\n----\n");
printf("1-Search By Character\n2-Search By Word\n3-Search By Length\n0-Quit\nPlease enter a selection: ");
int selection;
scanf("%d", &selection);
switch(selection)
{
case 0:
menuActive = 0;
break;
case 1:
printf("Selected 1\n");
printf("Enter a character to search: ");
char characterSearch;
scanf(" %c", &characterSearch);
int characterwordCount = searchByCharacter(textInput, textLines, characterSearch);
printf("\nNumber of occurence of %c = %d", characterSearch, characterwordCount);
break;
case 2:
printf("Selected 2\n");
printf("Enter a word to search: ");
char wordSearch[MAX_LINE_LENGTH];
scanf(" %s", wordSearch);
int lengthwordCount = searchByWord(textInput, textLines, wordSearch);
printf("\nNumber of occurence of %s = %d", wordSearch, lengthwordCount);
break;
case 3:
printf("Selected 3\n");
printf("Enter search length: ");
int wordLength;
scanf(" %d", &wordLength);
int wordLengthwordCount = searchByLength(textInput, textLines, wordLength);
printf("Number of words with length %d = %d", wordLength, wordLengthwordCount);
break;
default:
printf("Invalid Input.\n");
}
}
printf("You Have Quit!\n");
}
return 0;
}

Why does it say 'expected declaration specifiers before 'main''

first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}
By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}
int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.

C Using array values erases array

I am confused, when i use array values to assign another array values. the original array deletes the values used
int main(int argc, char *argv[]) {
char original[ORIGINAL_SIZE];
int isbn[ISBN_SIZE];
int index = 0;
int code;
int weight = 10;
int weightedValue;
int weightedSum = 0;
printf("Enter an ISBN to validate: ");
validateISBNArray(original);
while(index < ORIGINAL_SIZE){
if(original[index] != '-'){
if(original[index] == 'x' || original[index] == 'X') isbn[index] = 10;
else if(original[index] == 0) isbn[index] = 0;
else isbn[index] = original[index]-48;
code = isbn[index];
//printf("%d", code);
weightedValue= code*weight;
weight--;
weightedSum += weightedValue;
}
index++;
}
printf("%s",original);
if(weightedSum%11==0) printf("The ISBN %s, is VALID", original);
else printf("The ISBN %s, is NOT VALID", original);
return 0;
}
validateISBNArray has no effect on original array
this is the code for the not affecting function
void validateISBNArray(char array[]){
int index = 0;
int countDigits = 0;
int value = 0;
clearArray(array, ORIGINAL_SIZE);
scanf("%s",array);
while(index < ORIGINAL_SIZE){
//printf("%d %c %d\n", index, array[index], countDigits);
if(((array[index]-48) >= 0 && (array[index]-48) <= 9) || (array[index] == 'x'|| array[index] == 'X')) {
countDigits++;
index++;
}
else if(array[index] == '-' || array[index] == 0) index++;
else{
printf("INVALID CHARACTER %d = %c. Please Enter Digits Or/And Hyphens Only: ", index, array[index]);
index = 0;
countDigits = 0;
clearArray(array, ORIGINAL_SIZE);
scanf("%s",array);
}
if(index == ORIGINAL_SIZE && countDigits != 10){
printf("INVALID NUMBER OF DIGITS %d. Please Enter 10 Digits: ", countDigits);
index = 0;
countDigits = 0;
clearArray(array, ORIGINAL_SIZE);
scanf("%s",array);
}
}
//printf("%s", array);
}
Ok I fixed it removing the need for the isbn array
int main(int argc, char *argv[]) {
char original[ORIGINAL_SIZE];
int isbn[ISBN_SIZE];
int index = 0;
int code;
int weight = 10;
int weightedValue;
int weightedSum = 0;
printf("Enter an ISBN to validate: ");
validateISBNArray(original);
while(index < ORIGINAL_SIZE){
if(original[index] != '-'){
if(original[index] == 'x' || original[index] == 'X') code = 10;
else if(original[index] == 0) code = 0;
else code = original[index]-48;
weightedValue = code*weight;
weight--;
weightedSum += weightedValue;
}
index++;
}
if(weightedSum%11==0) printf("The ISBN %s, is VALID", original);
else printf("The ISBN %s, is NOT VALID", original);
return 0;
}

End a program with the Enter key

I am trying have a program end when the user hits the Enter key. For some reason it doesn't seem to work. When I use "char c is not equal to enter key" it takes in an extra integer in c (the last inputted integer). What is the problem with this code?
#include <stdio.h>
#include <stdlib.h>
#define framenumber 4
int test1 =0;
int test2=1;
int main(void)
{
int mainarray[framenumber][2] = {0}, nHP = 3, takein, iPT;
char c = getchar();
printf("Enter: ");
while(1)
{
char c = getchar();
if(c == '\n') {
printf("here");
}
else
{
printf("not enter\n");
takein = atoi(&c);
for (iPT = 0; mainarray[iPT][test2] != takein && iPT < framenumber; iPT++);
if (mainarray[iPT][test2] != takein)
{
//search for a victim
do {
nHP = (nHP + 1) % framenumber;
} while ( !( mainarray[nHP][test1] == 1 ? mainarray[nHP][test1] = 0 : 1 ) );
//update the page table
mainarray[nHP][test1] = 1;
mainarray[nHP][test2] = takein;
}
else
{
mainarray[iPT][test1] = 1;
}
puts("page table:");
for (iPT = 0; iPT < framenumber; iPT++)
{
printf("%s %d, %d.\n", iPT == (nHP + 1) % 4 ? ">": " ", mainarray[iPT][test1], mainarray[iPT][test2]);
}
putchar('\n');
printf("Enter: ");
}
}
return 0;
}
Do not create block variable. (In while loop).
char c='\0'; /* initialize with 0 */
printf("Enter: ");
while(c!='\n') /* loop terminate condition */
{
c= getchar(); /* remove declaration */
if(c =='\n')
{
printf("here");
}
else
{
getchar(); /* read (eat) an extra input */
printf("not enter\n");
....

Resources