Anyone got anything about reading a sequential number from text file per line and parsing it to an array in C?
What I have in a file:
12 3 45 6 7 8
3 5 6 7
7 0 -1 4 5
What I want in my program:
array1[] = {12, 3, 45, 6, 7, 8};
array2[] = {3, 5, 6, 7};
array3[] = {7, 0, -1, 4, 5};
I've been through several ways to read it, but the only matter is only when i want to tokenize it per line. Thank you.
The following code will read a file a line at a time
char line[80]
FILE* fp = fopen("data.txt","r");
while(fgets(line,1,fp) != null)
{
// do something
}
fclose(fp);
You can then tokenise the input using strtok() and sscanf() to convert the text to numbers.
From the MSDN page for sscanf:
Each of these functions [sscanf and swscanf] returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.
The following code will convert the string to an array of integers. Obviously for a variable length array you'll need a list or some scanning the input twice to determine the length of the array before actually parsing it.
char tokenstring[] = "12 23 3 4 5";
char seps[] = " ";
char* token;
int var;
int input[5];
int i = 0;
token = strtok (tokenstring, seps);
while (token != NULL)
{
sscanf (token, "%d", &var);
input[i++] = var;
token = strtok (NULL, seps);
}
Putting:
char seps[] = " ,\t\n";
will allow the input to be more flexible.
I had to do a search to remind myself of the syntax - I found it here in the MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With