hey guys , its my first but hopefully not last post , i have this wordcounter(actually recepie reader) project it looks for the word "csoki" given in input and then if it finds it it asks perfcentage of "csoki"(short for chocholate in my lang) and stores the value in array for future references(SUMming , etc) that i have not yet done


[every recepie name should have a value in the t[] array(representing the % of chocholate in the recepie) and the jcs var should mark the number of the current recepie]

t[jcs]=getchar();
				while (t[jcs]>100 || t[jcs]<1){
				printf("\n 1-100on kívülit adtál meg ! Add meg újra a csokiarányát \n");
				t[jcs]=getchar();
				}

my problem is this part ,
it should read input into the current and if its not a percentage in 1-100 it should tell the user to re-input , but it does not seem to work , it doesnt ask for repeat after a bad value , it also repeats things that it shouldnt from the main function ...

#define MAX 120
#define NEV "csoki"
#include <stdio.h>
#include <string.h>
#include <conio.h>


int getline(char s[],int lim) {
  int i,c;

  for (i=0;i<lim && (c=getchar())!=EOF && c!='\n';++i) s[i]=c;
  s[i]='\0';
  while (c!=EOF && c!='\n') c=getchar();
  return i;
}

int szame (char s[]){
int i;
for (i=strlen(s)-1;i!=0&&s[i]>='0'&&s[i]<='9';--i);
if (s[i]>='0'&&s[i]<='9')
 return 1;
else return 0;}

int strkmp(char s1[], char s2[]) {
  int i,e,h;
  h=0;
  i=0;
  e=-1;
  
	while (e<80){
		++e;
		if (s1[e] == s2[0]){
			while (s1[e]==s2[i]){
				++e;
				++i;
				++h;
				if (i>4){
					printf("%d - %d karakter volt a csoki  \n\n",e-4,e+1);
					return 1;
				}
			}
		}
	}
  return 0;
}

void main(void) {
  int db,jcs,w,t[80];        /*Hányszor találtuk meg NEV-et az inputban */
  char s[MAX+1]; /* Az aktuális név */

   db=0;
  jcs=-1;
  w=0;

  printf("Adjon meg ENTER-rel lezártan recepteket, és a program\n"
	 "megszámolja, hogy szerepel-e a %s bennük.\n"
	 "Befejezés üres sorral.\n",NEV);
 
	  while (getline(s,MAX)!=0)
		  if (strkmp(s,NEV)==1){
			++db;
			++jcs;
			printf("\nVan benne csoki! \nCsokitartalma százalékban ?    (1től - 100ig)\n");
			t[jcs]=getchar();
				while (t[jcs]>100 || t[jcs]<1){
				printf("\n 1-100on kívülit adtál meg ! Add meg újra a csokiarányát \n");
				t[jcs]=getchar();
				}
			printf("\n %d -be volt eddig csoki\nkövetkező recept ?\n",db);
		}
		else{
			printf("nincs benne csoki\nkövetkező recept ?\n");
			++jcs;
		}
	  getchar();
}

Recommended Answers

All 17 Replies

If the test portion of the while(test in here) doesn't resolve to 1 (true), then the inner part of the while() loop will not be entered by the program.

So, is t[jcs] > 100, right at the top of the first loop?

And somewhere in the while() loop, you want to increment a variable (i is the standard syntax, but any integer variable name will work:

i=0;
t[i] = 99;
while(t[i]<100) {
  printf("i = %d", i);
  ++i;
  t[i] = getchar();
}

Without the ++i, the program would always put one value, right on top of the other one, in t. Be careful not to confuse the value of t with the value of i.

Welcome to the forum, TomaCukor! ;)

t[jcs]=getchar();
				while (t[jcs]>100 || t[jcs]<1){
				printf("\n out of 1-100 range , re-enter value\n");
				t[jcs]=getchar();
				}

yes if while () is 1 then it should enter my while loop(that means he gave bad input the first try , before the loop) , and i have an OR set up in middle , so if any of them are 1 it should enter

im fine with putting the new value in the place of old one i wanna make it to prompt user till he enters a valid one(not letting him out of loop till the check isnt 0)

You realize that getchar is reading one character and returning the code value of that character, right? If you type "100", the values you get are likely to be 49, 48, and 48. Is this intended? Because it raises red flags when I read it.

Why not have the user input an integer, instead of a char, (as mentioned above), and use a do while loop, instead of a while loop? That will put the test for what the user entered, AFTER they have entered the loop, instead of right at the top of it.

(This can be done with a while loop, but the logic has to be changed. It's more intuitive to use a do while loop, for clarity.)

You realize that getchar is reading one character and returning the code value of that character, right? If you type "100", the values you get are likely to be 49, 48, and 48. Is this intended? Because it raises red flags when I read it.

no i didnt realize ... i thought its enuff to declare both jcs and the array as ints , got it to work now using scanf .... is there any getchar equivalent for ints ? its a shame for such a simple command , that it cant read int and have to use scanf ..

do{
printf("\nCsokitartalma százalékban ?    (1től - 100ig)\n\n");
scanf("%d",&t[jcs]);
} while (t[jcs]>100 || t[jcs]<1);

now my project works much healthier , thanks guys ! ill keep it open till i finish(if its allowed) , cuz im sure ill run into some other things

There's no way to use a function that only takes one key input, and use it for to input an integer. No, since an integer might contain several digits.

You're asking if there is a trash can, that can haul the garbage truck. Clearly not.

>is there any getchar equivalent for ints ?
If you mean something super simple like int x = get_int(stdin); then no. A usable function along those lines can easily be written though:

#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <errno.h>

int get_int(FILE *in, unsigned *n_digits)
{
    const unsigned base = 10;
    const unsigned safe = UINT_MAX / base;
    const unsigned lsd = UINT_MAX % base;

    unsigned overflow = 0;
    unsigned sign = 0;
    unsigned temp = 0;
    unsigned n = 0;
    int value = 0;
    int ch;

    if ((ch = getc(in)) == '-' || ch == '+') {
        sign = ch == '-';
        ch = getc(in);
    }

    for (; isdigit(ch); ch = getc(in), n++) {
        unsigned digit = ch - '0';

        overflow = temp > safe || (temp == safe && digit > lsd);

        if (overflow)
            break;

        temp = temp * base + digit;
    }

    ungetc(ch, in);

    if (n > 0) {
        if (overflow || (sign && temp > -INT_MIN) || (!sign && temp > INT_MAX))
            errno = ERANGE;

        value = sign ? -(int)temp : (int)temp;
    }

    if (n_digits != NULL)
        *n_digits = n;

    return value;
}

int main(void)
{
    unsigned n = 0;
    int x = get_int(stdin, &n);
    int ch;

    if (errno == ERANGE)
        fprintf(stderr, "Error: Number exceeds [%d, %d]\n", INT_MIN, INT_MAX);
    
    if (n == 0)
        fprintf(stderr, "Error: No integer detected\n");
    else
        printf("Detected %d with %u digits\n", x, n);

    fputs("Characters remaining: '", stdout);

    while ((ch = getchar()) != '\n')
        putchar(ch);

    puts("'");

    return 0;
}

so now im trying to read integers from input untill input is eof or blank line(line was left empty and enter was hit) ... ive found some codes(getline ) but it only applies for char type ! and i dont want to go through the whole conversion thing(but if theres a simple one ill consider it) ! what is have is

do {
	scanf ("%d",&t[e]);
		i=t[e];
	printf("\n%d\n",i);
	if (i> 9 && i<20){
		printf("jo a szam!");
		while (c<21){
			c++;
			printf("%d", t[c]);
			}
	}
	} while (1);

so basically id like to change my do -while , this part

} while (1);

to a "end at blank line"(end program after hitting enter) OR eof cycle break (coming from line2 scanf output(i))

(somthing roughly like this(its from getline))

for (i=0;i<lim && (c=getchar())!=EOF && c!='\n';++i)

a wild guess is

while (i!=EOF && i!='\n')

but doesnt seem to work

so now im trying to read integers from input untill input is eof or blank line(line was left empty and enter was hit) ... ive found some codes(getline ) but it only applies for char type ! and i dont want to go through the whole conversion thing(but if theres a simple one ill consider it) !

Why do you want to do it the hard way and not the easy way?

Read the line.
Test if it's blank.
If not, test if it's digits (this is simple).
If so, convert to binary (also simple, one statement).

thanks ive got passed that

now id like to know how do i get my program to handle a blank line with the "else if"
cuz the else is already handled with the message "its not a number"
theres three options now ,
1, if its a number , the program stores it
2, if its a blank like , the program exits the loop and goes on
3, if its a letter , the program asks for it again

in the second one im a bit stuck :(

while (k==1)
  { 
if(getline(sor,MAX)>0 && szame(sor) && sor!=0) {
	    printf("\n elso eset %d\n",i);
	   s_i[i]=atoi(sor);
	   ++i;
	   f=i;}
	else	if  (s_i[i-1]==EOF || s_i[i-1]=='\n'){ 
			k--;
			printf("\n üres sor érzékelve , megszakítás\n");
		}
   else
    {
			    printf("\n harmadik %d\n",i);
     printf("\n\n  Ez nem sz m! K‚rem nyomjon egy billentyűt. . .\n");
     getch();
    }
}

so i regrouped it , but my problem is , that my isdigit(name szame here) is handling blank lines !!

while (k==1)
  {
   if(getline(sor,MAX)>0 && szame(sor)) {
	    printf("\n elso eset %d\n",i);
	   s_i[i]=atoi(sor);
	   ++i;
	   f=i;}
   else	if(szame(sor)==0) { 
     printf("\n\n  Ez nem sz m! K‚rem nyomjon egy billentyűt. . .\n");
     getch();
   }
   else{
	k--;
	printf("\n üres sor érzékelve , megszakítás\n");
		}

  }

id like somthing here to activate only on blank line

else if

or deactivate the "blank line" handling in the other checks so i can put it in else

sorry double

Get the line then start testing. Don't get it in the IF statement.

i did think of that too , but i still dont know how i can handle blank lines

while (k==1)
  {
	 g=getline(sor,MAX);
   if(g>0 && szame(sor)) {
	   printf("\n elso eset %d\n",i);
	   s_i[i]=atoi(sor);
	   ++i;
	   f=i;

 else if(s_i[i-1]=='/0'){ 
		k--;
	        printf("\n üres sor érzékelve , megszakítás\n");}

  
   else{
       printf("\n harmadik %d\n",i);
       printf("\n\n  Ez nem szam! addj meg szamot!\n");
	   	
   }
}

Start with (in your case) the hardest test first.

if line is blank
   exit loop
else
   if line is #
      convert it
   else
      bad line

looks like i got it
i put the whole thing in a "while"
so i didnt need the "else if"

while ((g=getline(sor,MAX))!=0)
  {
	 h=szame(sor);
	 s_i[i]=atoi(sor);

   	    if(g>0 && h) {
	    printf("\n elso eset %d\n",i);
	   ++i;
	   f=i;{ 
   }
   }
   else{
     printf("\n harmadik %d\n",i);
     printf("\n\n  Ez nem szam! addj meg szamot!\n");

now id like to ask about another project

this loop seems to be infinate , but id like it to just reapeatedly ask the user to input untill user inputs a valid value within range (1-100 thats the check in the end) , but it doesnt stop to ask

do{
	printf("\nCsokitartalma százalékban ?    (1től - 100ig)\n\n");
	scanf_s("%d",&t[jcs]);
	} while (t[jcs]>100 || t[jcs]<1);

Other than using the non-Standard scanf_s() I don't really see a problem. Try displaying t[jcs] after the input to make sure it was input correctly.

More info is probably needed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.