Parameters inside the function - c

I have a work to do in which I have to keep a loop inside the function expecting the following parameters:
-"i" to insert
-"s" to search
-"q" to quit
How do I keep this loop? I've looked up some options and it seems to be possible using a while or a switch, but I am not sure which is the best way to read those chars (with a fscanf perhaps?). I am also not sure how to read the things after the parameter "i" as the input would be "i word 9", so after detecting the i to insert I have to read a string and an int.
Anyone has any idea how to do this? I am sorry is this seems simple, but I am new to programming.
edit: Here is what I have so far
while (loop) {
fscanf(stdin,"%c",&par);
if (strcmp(&par,"i")){
scanf("%s %d",palavra,p);
raiz = insere(raiz,&palavra,p);
}
else if (strcmp(&par,"b")){
scanf("%s",palavra);
busca(raiz,&palavra);
}
else if (strcmp(&par,"q"))
loop = 0;
}
edit 2: This is what I have now, I am having problems reading the string and integer when the parameter is i, somehow it crashes the function
while (1) {
c = getchar();
if (c == 'f')
break;
else if (c == 'i'){
fscanf(stdin,"%s",&palavra);
scanf("%d",&p);
raiz = insere(raiz,palavra,p);
}
else if (c == 'b') {
scanf("%s",palavra);
busca(raiz,palavra);
}
}
Thanks in advance!

The code you have doesn't look too bad compared to what I believe you want. You can replace the "while (loop)" with "while (1)" and then your exist code "loop = 0;" with "break;" which is a bit more standard way of doing things. Also "fscanf(stdin..." is the same as "scanf(..." ... scanf will read from stdin by default. You might want to check the docs for strcmp because it returns 0 for an exact match and I don't think that will do what you want in your 'if' statements. You should be able to use scanf to read in the values you want, is it giving you an error?

You are using 3 separated scans. That means you can't input this "i word 9", but input one command or parameter at the time separated by EOL(pressing enter).. i, enter, word, enter, 9, enter ... Then the function should actually get further in those "if"s. With those scans you also should consider printing information about expected inputs ("Choose action q/i/f")
And I would recommend using something to test those inputs.
if (scanf("%d", &p) == 0) {
printf("Wrong input");
break;
}

Related

Something strange with if() in c

This is for a school project I'm working on, it's just a small part of the code but for some reason the program doesn't seem to go inside the if() no matter what the input is. I've tried anything and everything I know of (also used the isalpha() function) but it just won't run the commands inside the if().
do
{
flag=1;
gets(input.number);
printf("\n%s\n",input.number);
for(i=0;i<strlen(input.number);i++)
{
printf("yolo1\n"); //debug
if(input.number[i]<48 || input.number[i]>57) //PROBLEM HERE
{
printf("\nyolo2\n"); //debug
flag=-1;
break;
}
}
if(strlen(input.number)<1000 || strlen(input.number)>9999 || flag==-1) printf("\nINVALID INPUT\n\nARI8MOS: ");
}while(strlen(input.number)<1000 || strlen(input.number)>9999 || flag==-1);
Can you guys help me out here??? I've been staring and the code for the better part of 3 days now....
I presume you declared char input.number[].
Your condition in if says that you only want to get into its body if the character is NOT a digit. This is somehow contradictory to the name input.number of the variable (but perhaps you are just checking for incorrect characters here...)
To better see what is happening with the condition, you can choose to print the values of its components, like this:
printf("%c[%d]", input.number[i], input.number[i]);
printf("%d, %d, %d\n", input.number[i]<48 , input.number[i]>57, input.number[i]<48 || input.number[i]>57);
(you will se a 0 for false and 1 for true)
BTW: You could write the same condition in a more readable manner, using char constants like this:
input.number[i]<'0' || input.number[i]>'9')

Why does my function return 0 instead of the number of lines in a file?

I have written a function that is supposed to read the number of sentences in a .txt file, but when the function is called and done, it gives me a value of 0.
This program over all has 3 more functions to figure out different properties of the file and I have them working great. This one is laid out the same way I wrote my other functions just looking for some advice on why I am getting 0 as my number of sentences.
void ptrCntS (FILE* sp1, int sCount)
{
char sentence = 'O';
int myChr;
if (!(sp1 = fopen("Hello.txt", "r")))
{
printf("error opening Hello.txt");
return(1);
}
while ((myChr = fgetc(sp1)) != EOF)
{
if ('.')
{
sentence ='O';
}
else if (sentence == 'O')
{
sCount++;
sentence = 'I';
}
}
fclose(sp1);
printf ("Total number of sentences are:\t%d", sCount);
return;
}
instead of return use return(sCount);
and assign the return value to some int variable in calling function
like
int sentCount;
.
.
.
sentCount=ptrCntS (param1,param2);
if ('.') is always true, thus else... code never reached. Use if( myChr == '.' ) instead.
Function compiles now and runs properly. This function is being called from a switch in a previous function where I had my addresses set and included my print statement for the totals so that I would not have to write another function in the end to call on all my counts and print their results. Instead I set my case 'A': to call all of my counting functions(in this case that is what the original code is) and than display my results. I am sorry for any lengthiness or my hard to understand writing I am new to the C language and I am having a hard time grasping the literature but making some process on understanding the syntax.

C: Scanf in while loop executes only once

I am trying something simple in C, a program to get the exchange and do some conversions.
To make sure scanf gets the right type I placed it into a while loop, which continues to ask for input until a number is inserted.
If I enter a character instead of a number it does not ask again for an input.
exRate = 0;
scanfRes = 0;
while(exRate <= 0){
printf("Enter the exchange rate:");
while(scanfRes != 1){
scanfRes = scanf(" %f", &exRate);
}
if(scanfRes == 1 && exRate > 0){
break;
}
printf("Exchange rate must be positive.\n");
}
UPDATE: As this is a course assignment, I was not supposed to use anything outside of the taught material. When I asked the academic staff about handling unexpected input, I got an answer that this is a scenario I am not supposed to take into consideration.
The answers and help in the comments is all useful and I added 1 to all useful suggestions. The staff answer makes this question no longer needed.
Change handling of scanf() result.
If the input is not as expected, either the offending input data needs to be read or EOF should be handled.
for (;;) {
printf("Enter the exchange rate:");
scanfRes = scanf("%f", &exRate);
if (scanfRes == 0) {
printf("Exchange rate must be numeric.\n");
// somehow deal with non-numeric input, here just 1 char read & tossed
// or maybe read until end-of-line
fgetc(stdin);
} else if (scanfRes == EOF) {
// Handle EOF somehow
return;
} exRate > 0){
break;
}
printf("Exchange rate must be positive.\n");
}
Note: the " " in " %f" is not needed. "%f" will consume leading white-space.

Advice on Segmentation Fault, using gdb effectively, C Programming (newbie)

I am having a problem with a segmentation fault working in C, and I cannot figure out why this is occurring. I think it has something to do with misuse of the fget(c) function.
while((ch = fgetc(fp))!= EOF) {
printf("Got inside first while: character is currently %c \n",ch); //**********DELETE
while(ch != '\n') {
char word[16]; //Clear out word before beginning
i = i+1; //Keeps track of the current run thru of the loop so we know what input we're looking at.
while(ch != ' ') {
printf("%c ",ch); //**********DELETE
//The following block builds up a character array from the current "word" (separated by spaces) in the input file.
int len = strlen(word);
word[len] = ch;
word[len+1] = '\0';
printf("%s",word);
ch = fgetc(fp);
}
//The following if-else block sets the variables TextA, TextB, and TextC to the appropriate Supply Types from the input.
//This part may be confusing to read mentally, but not to trace. All it does is logically set TextA, B, and C to the 3 different possible values SupplyType.
if(word!=TextB && word!=TextC && i==1 && TextB!="") {
strcpy(TextA,word);
}
else if(word!=TextA && word!=TextC && i==1 && TextC!="") {
strcpy(TextB,word);
}
else if(word!=TextB && word!=TextA && i==1) {
strcpy(TextC,word);
}
switch(i) {
case 1:
if(TextA == word) {
SubTypeOption = 1;
}
else if(TextB == word) {
SubTypeOption = 2;
}
else if(TextC == word) {
SubTypeOption = 3;
}
break;
case 2:
//We actually ultimately don't need to keep track of the product's name, so we do nothing for case i=2. Included for readibility.
break;
case 3:
WholesalePrice = atof(word);
break;
case 4:
WholesaleAmount = atoi(word);
break;
case 5:
RetailPrice = atof(word);
break;
case 6:
RetailAmount = atoi(word);
break;
}//End switch(i)
ch = fgetc(fp);
}//End while(ch != '\n')
//The following if-else block "tallys up" the total amounts of SubTypes bought and sold by the owner.
if(SubTypeOption == 1) {
SubType1OwnersCost = SubType1OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType1ConsumersCost = SubType1ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 2) {
SubType2OwnersCost = SubType2OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType2ConsumersCost = SubType2ConsumersCost + (RetailPrice *(float)RetailAmount);
}
else if(SubTypeOption == 3) {
SubType3OwnersCost = SubType3OwnersCost + (WholesalePrice*(float)WholesaleAmount);
SubType3ConsumersCost = SubType3ConsumersCost + (RetailPrice *(float)RetailAmount);
}
}//End while((ch = fgetc(fp))!= EOF)
Using gdb (just a simple run of the a.out) I found that the problem is related to getc, but it does not tell which line/which one. However, my program does output "Got in side the first while: character is currently S". This S is the first letter in my input file, so I know it is working somewhat how it should, but then causes a seg fault.
Does anyone have any advice on what could be going wrong, or how to debug this problem? I am relatively new to C and confused mostly on syntax. I have a feeling I've done some small syntactical thing wrong.
By the way, this snippet of the code is meant to get a word from a string. Example:
Help me with this program please
should give word equaling "Help"
Update: Now guys I am getting kind of a cool error (although cryptic). When I recompiled I got something like this:
word is now w S
word is now w Su
word is now w Sup
... etc except it goes on for a while, building a pyramid of word.
with my input file having only the string "SupplyTypeA 1.23 1 1.65 1" in it.
UPDATE: Segmentation fault was fixed (the issue was, I was going past the end of the file using fgetc() ). Thanks everyone.
If anyone still glances at this, could they help me figure out why my output file does not contain any of the correct numbers it should? I think I am probably misusing atof and atoi on the words I'm getting.
Make sure you compile the program with -g -O0 options
Next step through the program line by line in GDB, watch and understand what your program is doing. Look at the various variables. This is the essential debugging skill.
WHen it dies type the command 'k' this will give you a stack trace the last line of the trace will have the failing line number, but you know that anyway because you were on the line shen you did a step command
There is no "fget" in good old C, but maybe you're using a more modern version that has something named "fget". Most likely, you meant to use "fgetc". When a C I/O function starts with "f", it usually wants a FILE* handle as an argument, as "fgetc" does. Try using "fgetc" instead, after reading the documentation for it.

Switch and default: for C

Sorry if this sounds like a very basic question, it is my first time on here!
I am having some difficulties with coding for C, specifically with a switch and the default of that switch. Here is some example code:
#include<stdio.h>
int key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
switch(key){
case'0':
case'1':
case'2':
case'3':
printf("it's a numeral\n");
break;
default:
printf("it's not a numeral\n");
}
}
}
The actual code is a bunch longer, this is purely an example.
So the code compiles it and I execute it, but I get:
"You pressed 1, it's a numeral, you pressed , it's not a numeral."
My code seems to 'fall through' and repeat itself without referring to either one. If anyone could help that would be great as this is an example in a text book and I am utterly stuck!
Kindest Regards.
You need to account for entering the Enter key, which produces a '\n' on *nix systems. I am not sure what pressing the Enter key does on Windows systems.
Here's your original code doctored up to eat the return key.
#include<stdio.h>
int key = 0;
main()
{
while((key=getchar())!=EOF)
{
if('\n' == key)
{
/* Be silent on linefeeds */
continue;
}
printf("you pressed %c \n",key);
switch(key){
case'0':
case'1':
case'2':
case'3':
printf("it's a numeral\n");
break;
default:
printf("it's not a numeral\n");
}
}
}
You maybe using getchar() for a specific reason, but my experiences in C usually involved reading the whole line, and RTL functions like scanf will eat the line terminator for you.
You need to eat the newline character, that is put in the read buffer when you hit return.
Issue another call to getchar after or before the switch to solve your problem.
Here is an idea...immediately before the printf(), insert logic to ignore spaces and all control characters...
if(key <= ' ')
continue;
printf(...) ...
I dont know if that is the problem, but you have three case without a break. So you press key "1" and there is nothing to do for the programm and so ins go to the next case how is right and this is the default.
Although you take a char in an int-variable???
In your Example it is a better way to take a if-clause like this:
#include<stdio.h>
char key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
if(key == '0' || key == '1' || key == '2' || key == '3'){
printf("it's a numeral\n");
}
else {
printf("it's not a numeral\n");
}
}
Code is not tested. ;-)
The best way in bigger programms is to work with regular expressions.
I hope, this answer was helpful.
the problem might be due to, input buffer not flushing. when "1" is matched in the switch case, a newline character remains in the buffer.
try this,
fflush(stdin)

Resources