Reading into a txt file [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to C and have the following issue. This program is supposed to read in exam scores from a data file and store the output into a text file. The output is supposed to be the number of grades as well as the number of each letter grade.
Whenever I run it, it crashes.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *inFile;
int current;
int sum = 0;
int b;
int theGrades[100];
inFile = fopen("a.txt", "r");
b = fscanf(inFile, "%d", &current);
while(b != -1){
theGrades[sum] = current;
sum++;
b = fscanf(inFile, "%d", &current);
}
fclose(inFile);
for(int i=0;i<=sum;i++){
printf("%d" + theGrades[i]);
}
}

1) Check inFile (it must be valid pointer, not NULL)
2) Check sum counter (must be < 100)
3) printf("%d" + theGrades[i]); - what are you doing? Have you printf("%d", theGrades[i]); in mind?

Your for loop needs help
for(int i=0;i<sum;i++){ //not <=
printf("%d ", theGrades[i]); // comma, not a plus sign
}
Also, check fopen for failure. Ensure you don't add more than 100 items. Use EOF instead of -1.

Related

Use of fgets in c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to write a program which converts a number from one base to another.
i need to get a user input in the form of: <original base><new base><number in original base>
I’m not allowed to use scanf and also im not allowed to assume the size of the line.
I have already tried using fgets() but I don’t know how to use it without limiting the size. I would love to get some ideas of what to do. Thanks.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int BaseChanger()
{
char input[12];
printf("enter the original base, new base ,number");
fgets(input, 12, stdin);
}
You can use this snippet as a form of getline
int max= 100;
char* array;
array = malloc(max*sizeof(char));
if(array == NULL)
exit(1);
int c,i=0;
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
array[ i++ ] = c ;
if( i == max)
{
char * narray = realloc(array, max *= 2);
if( narray == NULL ){
free(array);
exit(1);
}
array = narray;
}
...
}
Once you do this, extract the numbers and then do the rest of the logic.

How to use fscanf to read doubles 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 5 years ago.
Improve this question
I am currently writing a program that takes in an unknown number of doubles, each on their own line from a text file. It should be placing of these elements read into an array, but it isn't working. My print loop works, but it only prints zeroes. I've tried a lot of things and looked up a lot before coming here. This is my code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Open an file to read from
FILE *file;
file = fopen("data.txt","r");
if (file == NULL)
{
printf("File not found.");
return -1;
}
//Count the number of lines in the input file
int numLines = 0; //CHANGE TO 1 ???
int ch;
do
{
ch = fgetc(file);
if (ch == '\n')
numLines++;
} while (ch != EOF);
//Put all of the data read into an array;
double input[numLines];
int i = 0;
while ((fscanf(file, "%lf\n", &input[i])) == 1)
i++;
//Close the file
fclose(file);
//Test printing elements of array
for (i = 0; i < numLines; i++)
printf("%lf\n", input[i]);
return 0;
}
OP's test of fscanf() result is good, except code did not also check if too many numbers were in the file.
while ((fscanf(file, "%lf\n", &input[i])) == 1)
i++;
Then code ignored that last value of i and instead printed numLines times, even if fewer were successfully scanned.
for (i = 0; i < numLines; i++)
printf("%lf\n", input[i]);
End code should have been
while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
i++;
for (j = 0; j < i; j++)
printf("%lf\n", input[j]);
This would have printed 0 lines! The file needed to be reset for a second pass. #paulr
rewind(file);
while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
...
A further problem is assuming the count of '\n' is the same as the count of numbers. This can easily be fooled given multiple numbers per line or the last line having a number yet no '\n'.
A simple work-around it to make the input[] 1 larger and use the actual scan success count as the count of numbers to print. More robust code would read 1 line at a time with fgets() and include additional error checks.

How to increase array size that has global pointer in each loop [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
I want to set the size of an array as the first integer in a text file (say 5). If I saved all the 5 integers that follow the size into the array, and there is still lines in the input file, I need to increase the size of the array each time and store that line (integer) in the array.
I wrote this code:
int *x;
int *sizeP;
int main(int argc, char *argv[]) {
int decision;
FILE* file = fopen( argv[1], "r" );
int size;
fscanf(file, "%d", &size);
sizeP = &size;
x=malloc(size*sizeof(int));
int p=0;
int num;
while(fscanf(file, "%d", &num) ) {
x[p] = num;
p++;
if (p >= size) {
puts("Enter 0 to continue or 1 to terminate");
scanf("%d", &decision);
break;
}
}
if (decision == 0){
while(fscanf(file, "%d", &num) ) {
size++;
x = (int*)realloc(x, size*sizeof(int));
x[p] = num;
p++;
}
free(x);
}
}
I am not sure what is wrong with this code?
Thank you in advance.
Your way of checking the result of fscanf is not correct. When the end of file is reached, fscanf does not return 0, but EOF, which is not zero (it is defined as -1 on most platforms).
while(fscanf(file, "%d", &num) )
This will enter an infinite loop once the end of the file is reached, because since EOF is not zero, its boolean value is true.
The correct way to check the result of fscanf is to compare it with the number of fields expected. Since you are reading one value, you should the return like like this:
while(fscanf(file, "%d", &num) == 1) // <-- return value should be 1 on success

Converting floating point csv to 2d array in c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to convert a floating point csv to a 2D array in c. Have already saw an article (Import CSV elements into a 2D array in C) which explains the conversion to an integer array.Can any one help in modifying this code or a new approach that i could use to convert the csv to a floating point 2D array
for eg: my csv contains values like 0.018869,0.015863,0.044758,0.027318,0.049394,0.040823,..... and is a 4400*500 values csv. so i would need to use a big array of size 4400*500 to include all of these values.
Thanks in advance
Use atof() to convert strings to floats.
Here is a link if you want to read up on it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//counters
int i = 0;
int j = 0;
int k = 0;
char c = 0; //for storing a char at a time
char result_char_array[4] = {0}; //float is a 32 bit number, so 4 bytes
FILE *filep; //pointer to file structure
float results[100] = {0}; //to store the float
int main(void)
{
filep = fopen("C:/Documents/test.csv", "r"); //open file , read only
if (!filep)
{
fprintf (stderr, "failed to open file for reading\n");
return -1; //return negative number so you know something went wrong
}
c = fgetc(filep); //get first character
while(c != EOF)
{
if((c == ',') || (c == '\n')) //we want to stop at each comma or newline
{
//i = 0; //reset the count
results[j] = atof(result_char_array); //this converts a string to a float
j++; //increment j
memset(&result_char_array, 0, sizeof(result_char_array)); //clear the array
}
else
{
strncat(&result_char_array, &c, 1);
}
c = fgetc(filep); //get next character
i++;
}
results[j] = atof(result_char_array); //convert last number
fclose (filep); //always close the file
for(k = 0; k <= j; k++)
{
printf("Number %d is: %f\n",k, results[k]); //loop through the results and print line by line
}
getchar();
return 1;
}
Take a look at libcsv, which is a CSV library written in ANSI C89. But be careful, libcsv is licensed under LGPL.

Program to remove all the consecutive same letter from a given string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to develop a logic that will remove all the adjacent duplicate characters from a string.
For example:-
Input: azxxzy
Output: ay
Here is the logic that I have developed in C:
int main()
{
char str1[10], str2[10];
int n, i=0, j=0,z=1, k=0;
scanf("%d", &n);
for(i=0; i<n; i++){
gets(str1);
str2[0]=str1[0];
for(j=1; str1[j]!='\0'; j++){
if(str1[j] == str1[j-1])
continue;
else
str2[z] = str1[j];
z++;
}
for(k=0; str2[k]!='\0'; k++)
printf("%s\n", str2[k]);
}
return 0;
}
While executing the code it is throwing a compile error. What might be the problem?
printf("%s\n",str2[k]);
str2[k] is a char, but you tell printf it is a char*
But this program still will not work properly - the first call to gets() will just read the carriage-return that is left in the input queue after reading the initial int value. And you never null-terminate str2.

Resources