Why is my code ignoring the while? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So here is the code, it ignores the while and I don't know why, it is supposed to start with the while as soon as you enter a value for the first printf
#include <stdio.h>
int main()
{
str WhoOwes,Fabri,Alen,Amilcar,Maxi,Lolo;
int RandomInt=0,Deudores;
printf("How many people owes?:");
scanf("&d",&Deudores);
while(RandomInt <= Deudores);
{
printf("who owes?:");
scanf("&c",&WhoOwes);
if(scanf("%c",&WhoOwes)==Fabri)
{
Fabri= Fabri+1;
printf("Fabri debe $",Fabri*4);
}
}
return 0;
}
Thanks!H

Change:
while(RandomInt <= Deudores);
To (remove the semicolon):
while(RandomInt <= Deudores)
Also, the delimiter you use in scanf should be %d not &d.
Further more, what type is str?
You are using scanf delimiter%d which is for an int to store into a str type which, I assume is some sort of a struct. If it is, this is not the way to do that. You have to store information into each part of the struct separately. Or change the type str to an int. This could be the reason why your while loop doesn't happen because you are trying to compare an int to a str:
while(RandomInt <= Deudores); // Deudores is a str
Then you are reading information twice by calling scanf() twice but you are only comparing what you get the second time. Also, the first time you read it you use the &c delimiter which is invalid. It should be %c. Further more, you create the str Fabri variable above with an invalid type str and also you don't give it a value anywhere in your code so you cannot do the comparison in the if statement:
scanf("&c",&WhoOwes);
if(scanf("%c",&WhoOwes)==Fabri)
Since you are using the character delimiter %c, you should declare WhoOwes and Fabri as char types to have consistent logic although it isn't technically required since int and char store interchangeable information. You must also initialize the Fabri variable to some char value.
However, in the end of your code you have the statement:
printf("Fabri debe $",Fabri*4);
This will not work because you are missing a delimiter where to print the Fabri*4 value.
Change that line to:
printf("Fabri debe %d$",Fabri*4); // add the %d delimiter to print the actual value
Since you are using Fabri in a calculation, you should then probably declare all your variables as int and read them using the %d delimiter, not %c.
Your program should look something like this:
#include <stdio.h>
int main()
{
int WhoOwes, Fabri, Alen, Amilcar, Maxi, Lolo; // these are int types not str types
int RandomInt = 0, Deudores;
Fabri = 5; // initialize Fabri to some value that can be used for comparisons
printf("How many people owes?:");
scanf("%d",&Deudores);
while(RandomInt <= Deudores);
{
printf("who owes?:");
scanf("%d",&WhoOwes); // use
if(WhoOwes == Fabri) // use what you scanned the first time to compare to Fabri
{
Fabri= Fabri+1;
printf("Fabri debe %d$",Fabri*4); // add the int delimiter %d to actually print the money amount
}
}
return 0;
}

Related

C programming - Finding the necessary number in the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).

C Program stopped working after using scanf instead of var=0 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I have this code:
#include <stdio.h>
#include <stdlib.h>
int functie ( int v[], int nr, int z)
{
int i,count;
scanf("%d", &z);
for(i=0;i<nr;i++) {
if(z==v[i]) {
count=count+1;
}
}
return z;
}
int main()
{
int i,nr,z;
fscanf("%d", &z);
FILE *f;
FILE *g;
f=fopen("data-in.txt", "r");
fscanf(f,"%d",&nr);
int *v=malloc(nr*sizeof(int));
for(i=0;i<nr;i++) {
fscanf(f,"%d",&v[i]);
}
g=fopen("data-out.txt", "w");
fprintf(g,"%d %d", functie(v,nr,z));
fclose(f);
fclose(g);
free(v);
}
and before I had int z=0; instead of trying to scanf my var z.
When I run this I get a stopped working error.
I have an array with numbers (integers) read from file, first line is the number of elements and second line the elements.
I need a var lets say z to check how many times an element appears in vector (check if scanned number z is equal to an element and +1 count )
example:
in file
4 (cuz I have 4 elements )
1 2 3 3 ( my elements )
than scan z as 3
z==3 true
count=1
again
count=2
Two issues here, both in main. First:
fscanf("%d", &z);
This function expects a FILE * for the first argument, which you didn't specify. Presumably you wanted to read from the console instead, so use scanf:
scanf("%d", &z);
Second issue:
fprintf(g,"%d %d", functie(v,nr,z));
Your format string is expecting two integer arguments, but you're only passing in one. Get rid of the extra format specifier:
fprintf(g,"%d", functie(v,nr,z));
fscanf will not be delimited by newlines. Best thing to do is eat through file a line at a time with fgets. So, add a line buffer to the top of main:
char line[16]; // assuming integers will actually be small
After opening your file as above with 'f':
if (fgets(line, sizeof(line), f))
{
int count = atoi(line);
int *v = (int *) malloc(count * sizeof(int));
for (int i = 0; i < count && fgets(line, sizeof(line), f); ++i)
{
v[i] = atoi(line);
}
}
You should absolutely add error checking to the above, which is minimal and for concept only (e.g. guard against bad input, buffer overflow, exceptions, count being wrong leaving you uninitialized integers at the end of the array, etc.) as this will only work if your input file is perfect. Note that 16 is generally a ridiculously small length for a line buffer. Also only do your logic against your vector if (a) the file opens, and (b) passes the first test, which is an integral number of entries.

Why does my array still contain garbage values even after "clearing" them in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to obtain the first two strings from the first line of stdin using the following code.
#include <stdio.h>
#include <string.h> // for memset
int main(void) {
#define MAX_LINE_LEN 20
char heightWidth[MAX_LINE_LEN]; // allocate 50 chars to heightWidth
memset(heightWidth, 0, MAX_LINE_LEN);
fgets(heightWidth, MAX_LINE_LEN, stdin); // first line stored in heightWidth
char str1[MAX_LINE_LEN];
char str2[MAX_LINE_LEN];
memset(str1, 0, MAX_LINE_LEN);
memset(str1, 0, MAX_LINE_LEN);
int index = 0; // stores the current char index of str array
int strNumber = 1;
char currChar;
for (int i = 0; i < MAX_LINE_LEN; i++) {
if (strNumber > 2) { // if we've read two strings, break
break;
}
currChar = heightWidth[i]; // asssign current char to currChar
if (currChar == ' ') { // if current character is a space, continue
strNumber++; // increment strNumber
index = 0; // reset the index
continue;
}
// otherwise add it to one of our arrays
if (strNumber == 1) {
str1[index] = currChar;
} else {
str2[index] = currChar;
}
index++; // increment index
}
puts(str1);
puts(str2);
return 0;
}
However, when I enter three space separated strings or more, I sometimes get garbage values appended to the second string.
asdf 234 sdf // user input
asdf // first string printed is ok
234�� // second string has garbage appended
I initially though this was because the memory allocated to those arrays still had their previous values in them (hence my use of memset to "clear" them) but adding memset didn't seem to fix my issue.
What is the problem here and how can I edit my code to obtain two strings that are space separated?
You have a typo and instead of zeroing the second string you're zeroing the first one twice.
Ditch the memset calls (one of them has a typo as you are setting the same array twice), and write
char str1[MAX_LINE_LEN] = {0};
&c. instead. That will zero-initialise all the elements in the array. This is superior to using memset:
It reduces the possibility for bugs such as the one you have.
str1 and str2 are never in an uninitialised state.
You don't have to repeat the length of the array or conjure an expression (e.g. sizeof idioms) to impute it.
Reference for (3): https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

impacting Strings with pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The code which does not work. In function main after initializing variables by the user, it goes to if part and after that crash happens. This program's goal is to impact the repetitive characters in the string. So I decided to have a pointer in a function f1 and the pointer should point to 0th char of the array kar[]
then compare the 0th char to 1st char but the program crashes exactly after the last scanf("%s",kar[1000]).
where is the problem?
#include <stdio.h>
char f1(char* p)
{
int i=0,c=1;
while(*(p+i))
{
if(*p==*(++p))
{
c+=1;
p++;
i++;
continue;
}
else
{
if(c>1)
{
printf("%c%d",*p,c);
}
else
{
printf("%c",*p);
}
}
i++;
}
}
int main()
{
int n,i,m;
char kar[1000];
scanf("%d",&n);
for(i=1;i<=(2*n);++i)
{
scanf("%d",&m);
scanf("%s",kar[1000]);
if(m==1)
{
f1(kar);
}
}
}
This
scanf("%s",kar[1000]);
should trigger a compiler warning, as you pass a char where a char* is expected. You pass the 1001st element of kar (which is out of kar's bounds, BTW). In C array indices start with 0 for the 1st element.
To scan into kar, just pass the address of kar's 1st element.
scanf("%s", &kar[0]);
As arrays get decayed to the address of their 1st element when being passed to a function the following statement is equivalent
scanf("%s", kar);
Please note that the above two statements very well allow the user to enter more characters then kar can hold and with this make scanf() overflow kar, that is write beyond it bounds, invoking undefined behaviour, which might crash your program or whatever ...
To avoid this tell scanf() the maximum to scan by doing:
scanf("%999s", kar);
The maximum for chars a strings can hold in C is always one less then defined as C strings need one more char to have their end marked by a '\0'terminator.

scanf reading totally different number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Here is all the code I have in Visual Studio:
#include <stdio.h>
int main (void) {
int input;
puts("There are 10 seats available on the next flight");
puts("Where would you like to reserve a seat?");
puts("Please type 1 for First Class");
puts("Please type 2 for Economy");
scanf("%d", &input);
if (input == 1) {
printf("You Typed %d\n", &input);
}
if (input == 2) {
printf("You Typed %d\n", &input);
}
}
But when I run the program I get output that says:
There are 10 seats available on the next flight
Where would you like to reserve a seat?
Please type 1 for First Class
Please type 2 for Economy
1
You Typed 6159588
Press any key to continue . . .
I get a totally random number every time. Because of this I can't seem to get anything I write after the input to work. Why is this happening?
What you get printed out is the address of the variable input, not its value! This is because printf accepts its arguments by value - simply because they can be passed like that. What you need thus is
printf("%d", input); // without the ampersand!
scanf - in contrast - is fundamentally different. It is going to place a value into a variable you provide to it - and therefore needs a pointer.
Simple example:
int n = 7;
void myPrintf(int v)
{
++v;
}
void myScanf(int* v)
{
++*v;
}
int main(int argc, char* argv[])
{
myPrintf(n); // n passed by value, cannot be modified
// (but printf does not intend to, either!)
myScanf(&n); // n will be incremented!
// (scanf does modify, thus needs a pointer)
return 0;
}
Back to the roots, though: There is still a fundamental problem: You are passing a pointer, but evaluate it as an int. If sizes of both differ - which is the case on modern 64-bit hardware - you are in trouble. The value then is read from the stack with different size and part of your address actually gets discarded (pointer addresses require "%p" format specifier, assuring that the apprpriate number of bytes is read from stack - in case of modern systems 8 vs. 4 for int).

Resources