Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a results.txt file and on the seventh line I have numbers in form like:
3 5 6 1 9 7 4
I want to gather information how many of them > 5 and how many of them < 5.
How can I do this process for all of them?
By the way, the seventh line is the last line of the file.
Just read one line at a time and count. When you reach 7, that's your seventh line. Use fgets. Once you have the line you can use strtol in a loop to read each value as an integer.
Reference: fgets, strtol
To skip 1 line in the input file:
fscanf(f, "%*[^\n]\n");
To read 1 number from the file:
int number;
fscanf(f, "%d", &number);
To compare a number with 5:
if (number < 5)
{
...
}
P.S. The site http://www.cplusplus.com has some examples for the basic stuff you need. That site is dedicated to C++ but at your level there so little difference between C and C++, you can use the examples for your work (if you understand them).
Example: fscanf (at the bottom of the page)
#include <stdio.h>
#define LINE_MAX 1024
int main() {
int line_count = 7;
int fd = open('file', r);
int smaller_than_five = 0, bigger_than_five = 0;
int number;
while (line_count != 0) {
fgets(input_line, LINE_MAX, fd);
line_count--;
}
while(sscanf(input_line, "%d", &number) != EOF) {
if (number > 5) bigger_than_five++;
else if (number < 5) smaller_than_five++;
}
/*
* Now you have:
* smaller_than_five which is the count of numbers smaller than five
* bigger_than_five which is the count of numbers bigger than five
*/
return 0;
}
This works when the numbers are on seventh line. If they are on the last (but could be second or 51st), you'll have to change the first while to read while you have not reached the end.
Related
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 3 months ago.
Improve this question
int velikostVstupu=0;
while(scanf("%d", vstup+velikostVstupu)!=EOF){
velikostVstupu++;
if(velikostVstupu>2000){
printf( "Nespravny vstup.\n");
return 0;
}
}
This code is supposed to input no more than 2000 int values into my array "vstup[2000]". But nowhere do I check if the input is int, yet if it isn't, it succeeds my "if(velikostVstupu>2000)" (that's where I check if I am not over 2000).
Why is that? What is the math behind that?
scanf() may fail to read a number and return 0. Unless the input buffer changes it will do so forever till you reach your count limit. Each of arrays will be undefined after that point. You haven't told us how what that input looks like to handle the "skip non-numbers".
You overflow the array when you read entry with vstup == 2000 as the test is after you already read in the value (undefined behavior). This is how I would write it:
#include <stdio.h>
#define MAX_VSTUP 2000
int main(void) {
int vstup[MAX_VSTUP];
size_t velikostVstupu=0;
for(; velikostVstupu < sizeof vstup / sizeof *vstup; velikostVstupu++) {
if(scanf("%d", vstup+velikostVstupu) != 1)
break;
}
printf("Nespravny vstup %zu.\n", velikostVstupu);
}
and here are some example runs:
$ seq 1 | ./a.out
Nespravny vstup 1.
$ seq 2000 | ./a.out
Nespravny vstup 2000.
$ seq 2001 | ./a.out
Nespravny vstup 2000.
Thanks to #JonathanLeffler i think i know what is happening when inputing non number. it reads only until non number leaving the rest in buffer. When the next one asks it ignores white spaceses and he instantly finds a non number taking nothing and leaving buffer the same but incementing velikostVstupu. And this goes on until velikostVstupu>2000.
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.
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
There is a following exercise:
I have a file.txt containing a lot of unknown numbers, separated by one or more spaces or by a new line.(file.txt in one folder with my program).
I must find total amount of numbers and maximum value. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *in;
in=fopen("file.txt","r");
int arr[100],i=0,j,max;
while(fscanf(in,"%d",&arr[i] != EOF)) {
i++;
}
arr[0]=max;
for(j=1;j<i;j++) {
if(max < arr[j]) {
max = arr[j];
}
}
printf("Tot.number: %d\nMax: %d",i,max);
}
But, codeblock cannot execute the program.
fscanf(in,"%d",&arr[i] != EOF)
will be
fscanf(in,"%d",&arr[i]) != EOF
But there are other problems also
Not checking the return value of fopen.
if(in != NULL ){
/* File opened correctly */
}
No guard while accessing the array. if i>=100 there will be array index out of bound error leading to undefined behavior.
You forgot to declare initialize max.
You meant to initialize max to arr[0]. So correct will be max = arr[0]. There is no use assigning value of arr[0] in case you want to find the maximum.
Also you have to keep in mind that if fscanf doesn't return EOF then you can't be relieved that it worked unless you check that 2 value is being parsed correctly. The output of fscanf should be equal to 1 since one value is being read.
int r = fscanf("%d",&arr[i]);
if( r == 1 ){
/* SUCCESS */
}
else if( errno ) {
/* Error occured */
}
else if( r == EOF ){
/* Either EOF reached or some I/O error. */
}
Also among other things (not an error but a good practice)
Not closing the file.
fclose(in);
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 7 years ago.
Improve this question
I keep getting the output of 100 when I do what everyone else online has been posting about:
int total = sizeof(num)/sizeof(int);
It doesn't seem to work for me. Here's my code:
int main() {
static int num[100];
int totalNum = sizeof(num)/sizeof(int);
return 0;
}
void readNumbers(int* num) {
int i = 0;
FILE *fp;
fp = fopen("/Users/Documents/hello.txt", "r");
if (fp == NULL) {
printf("Could not load file");
exit(0);
}
/* Loads numbers into num array */
int number;
while(fscanf(fp, "%d", &number) > 0) {
num[i] = number;
i++;
}
}
My output is 100 so I'm assuming there isn't anything that is inserted into the num array? And if I print out sizeof(num) it gives me a hundred; 4 bytes * 100 = 400.
Here is what is in hello.txt:
14 21 39 48 109 3882
Unlike arrays in other languages (that can grow and shrink, and will tell you how many elements the array currently contains), a C array is just a simple block of memory that has a fixed size. You declared an array that can hold 100 elements, and that's all sizeof is going to tell you.
If you want to know how many numbers you've put in the array, then you have to keep track of that in a separate variable. The array itself doesn't contain that information.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have got a program to do as my homework. the program is simple. it asks to reverse the digits entered by the user and then print it using while loop. the problem arises when the user enters a number starting with zeroes.
For example:
Enter the number: 0089
The reversed number is : 9800
This is how the output should be. instead i get "98" as the answer.
and thanks in advance.
When asked to do someone else's homework, I like to devise an obtuse and compact way to do it.
void reverseNumber(void)
{
char c;
((c=getchar()) == '\n')? 0 : reverseNumber(), putchar(c);
}
Rather than reading the 0089 input as a numeric value, read it as a character array. This way the zeros won't be removed.
Read the numbers as a string.
And then use atoi() (stdlib.h) to make an integer number out if the string:
/* int atoi (const char *) */
Here is working code that makes exactly what your question requires:
// input: 0321
// output: 1230
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80] = {0}, temp_str[80] = {0};
int num, i, length = 0, temp_length = 0;
printf("Enter a reversed number (e.g. 0089): ");
scanf("%s", str);
length = strlen(str);
temp_length = length;
printf("string_length: %d\n", length);
for ( i = 0; i < length; i++ ) {
temp_str[i] = str[temp_length - 1];
/* The string length is 4 but arrays are [0][1][2][3] (you see?),
so we need to decrement `temp_length` (minus 1) */
temp_length--;
}
printf("temp_str: %s\n", temp_str);
num = atoi(temp_str);
printf("num: %d\n", num);
return 0;
}