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

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.

Related

Printf prints more character than those contained in my 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 5 years ago.
Improve this question
I have to write a program that acts like a shell. I wrote the function that gets the input from the user. I also wrote the function that splits it into arguments. The first time I type something, it works well, but the second time, it prints different characters after the ones that I gave it. I don't have to print it in the program. I was just doing it to see if it works correctly. I read a bunch of stuff online, but I can't figure out my error. I suppose it is in makeArgs(), but I can't pinpoint it.
Also, when I give it an input, the readline function adds a \n at the end of the string. I suppose it is from the fact that I press the enter key. I managed to solve the issue, by manually replacing it, but I would like to know if it is normal.
Any help really be appreciated.
Thank You
Screenshot of Xterm after 2 inputs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getText();
int makeArgs();
char *textEntre;
size_t nbCharacters;
char **arguments;
int main (void)
{
while (1){
getText();
int nbArguments = makeArgs();
for(int i =0; i<5; i++){
printf("%s \n",arguments[i]);
}
for(int i=0; i<nbArguments; i++){//free the char ptrs at the end
free(arguments[i]);
}
}
free(textEntre);
free(arguments);
return 0;
}
int getText(){
size_t buffersize = 0;
nbCharacters = getline(&textEntre, &buffersize, stdin);
textEntre[nbCharacters-1] =' '; // when I press enter it regiter the enter as \n so I replace it with a space
return 0;
}
int makeArgs(){
arguments = (char **)malloc(sizeof(char*)*20);
int i;
int j = 0;
int k = 0;
int nbElem = 20; //the number of ptrs that can be in arguments
for(i = 0; i<nbCharacters; i++){
if(i == 20){ //increases the memory allocated if there are more than 20 arguments
nbElem = nbElem *2;
arguments = (char **)realloc(arguments, sizeof(char*)*nbElem);
}
if(textEntre[i] == '"'){ //checks for ""
i++;
while(textEntre[i] != '"'){
i++;
}
}
if(textEntre[i] == ' ' && textEntre[i-1] == ' '){ // eliminates useless spaces
j++;
}
else if(textEntre[i] == ' '){ //save a single argument
char * chptr;
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
strncpy(chptr, &textEntre[j], i-j);
arguments[k] = chptr;
k++;
j = i +1;
}
}
return k;
}
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
You properly allocated memory for that terminating \0, but where do you actually add that "\0 at the end"?
strncpy(chptr, &textEntre[j], i-j);
strncpy does not necessarily zero-terminate the destination buffer. You have to do it yourself.
In fact, in this specific application strncpy is a rather inappropriate function: it does not give you anything over ordinary memcpy and might be less efficient. You could just do
memcpy(chptr, &textEntre[j], i - j);
with potentially better efficiency. And, again, don't forget to zero-terminate the destination buffer.
Or you can use sprintf for the same purpose as follows
sprintf(chptr, "%.*s", i - j, &textEntre[j]);
which will produce a properly zero-terminated string in the destination. (Albeit you won't see sprintf used that way very often.)

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.

Reverse the order of an integer in C [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 7 years ago.
Improve this question
I am currently learning C as part of a course and I have a task to reverse the order of a number without using any arithmetic (wording of the task).
I currently have this:
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (n != 0) {
reverse = reverse * 10;
reverse = reverse + n_10;
n = n / 10;
}
printf("Reverse of entered number is = %d\n", reverse);
return 0;
}
But this solution uses arithmetic. How can I alter this to complete the task?
From the exercise sheet, "though even at three
digits the naïve approach quickly grows unmanageable with arithmetic (try it!).
Your goal: Design 3-digit solution without using any arithmetic.(Hint: use scanf.)"
The wording of the question was confusing but to be clear the question is:
How do you reverse the order of a number, e.g. 123456789 to 987654321, without without using math. So the solution is to scanf to read the number and swap the numbers in a loop as the answer below.
You can just read it in as a string.
int main()
{
char str[80];
fgets(str, 80, stdin);
strrev(str);
printf("%s\n", str);
}
void strrev(char *str)
{
char *end, tmp;
end = str + strlen(str) - 1;
for (; end > str; --end, ++str) {
tmp = *end;
*end = *str;
*str = tmp;
}
}
I don't know if you consider pointer arithmetic to be "arithmetic"
Read as series of short strings that can hold 1 digit and then print in the reserve order.
char buf[10][2] = { 0 };
scanf("%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]",
&buf[0], &buf[1], &buf[2], &buf[3], &buf[4],
&buf[5], &buf[6], &buf[7], &buf[8], &buf[9]);
printf("%s%s%s%s%s%s%s%s%s%s",
buf[9], buf[8], buf[7], buf[6], buf[5],
buf[4], buf[3], buf[2], buf[1], buf[0]);
Obviously limited to max 10 digits.
A recusive approach, inpsired by #Nisse Engström. Works for any reasonable length input.
void pr(void) {
char digit[2];
if (scanf("%1[0-9]",digit)) {
pr();
printf("%s",digit);
}
}
int main(void) {
pr();
return 0;
}
Input
012345678901234567890123456789
Output
987654321098765432109876543210
Of course if (scanf("%1[0-9]",digit)) { should be if (scanf("%1[0-9]",digit) == 1) { to cope with EOF but that then may be "arithmetic".
Using scanf():
int
scanf (){
int
stdin =
getchar ();
return
stdin <0||
stdin ==
'\n'?
stdin :(
scanf (),
putchar (
stdin )),
'\n';}
int
main (){
putchar (
scanf ()
);}
Read integer, use sprintf() function to convert it into string and then use the library function strrev() to reverse the string.

Reading into a txt file [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 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.

Print every number with 0 in their digits (Only natural) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
The program requires a user to insert a number. Let's say we put 149. Now the program prints every number that has 0 digits in them till the number 149 (Including the number). So it's going to be 10,20,30,40,50,60,70,80,90,100,101...110..140 [Let's say the limit would be till 10000]
I have been trying to do this, but i only added +10 to every one, but that cannot be done >100 where it is 101,102..
Use the function sprintf to convert an integer to a string and then search for the character '0' in the string. If found, then print the number. Here's a simple working program implementing this idea.
#include <stdio.h>
#include <string.h>
#define MAXLEN 50 // max number of digits in the input number
int main(void) {
char buf[MAXLEN + 1]; // +1 for the null byte appended by sprintf
char ch = '0'; // char to be searched for in buf
int i, x;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
if(strchr(buf, ch)) // strchr returns a pointer to ch if found else NULL
printf("%d\n", i);
}
return 0;
}
You can also extract each digit of an integer in the given range and check it for zero. Here's a naive implementation.
#include <stdio.h>
int main(void) {
int i, x;
int r;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
for(r = i; r > 0; r /= 10) {
if(r%10 == 0) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
The simple approach would be to iterate through all natural numbers up to the target number and testing each of them to see if they have any zero digits. Note that the last digit of a non-negative integer i can be obtained as the remainder from division by the base (i % 10 here). Also remember that integer division in C truncates decimals, e.g., (12 / 10) == 1
As a start, consider to convert each number to char [] and then check whether it contains a '0' or not.
To read on:
How to check if a int var contains a specific number
Count the number of Ks between 0 and N
I think this would be the answer.
int j;
for(int i=1;i<150;i++){
j=i;
while(j>0)
{
if(j%10==0)
{
printf("%d\n",i);
break;
}
else
j=j/10;
}
}

Resources