how to make arrays from txt file C - c

I got text file with information: (100;200;first).Can anybody tell me how to seperate this information into three arrays: Min=100,Max=200 and Name=first. I have tried this whith
c=getc(inp);
i=atoi(szinput);
but its read 10 for first time and 00 for second... and so on in loop
c saves 10 not 1, so i cant get the right information for arrays...
So the array Min stores 1000 not 100
Thanks.

use scanf or fscanf like this:
scanf("(%d;%d;%[^)])",&min,&max,str);

You could do something like the following
FILE *file;
char readBuffer[40];
int c;
file = fopen("your_file","r");
while ((c=getc(file))!= EOF)
{
strcat(readBuffer, c);
if( (char) c == ';')
//this is the delimiter. Your min, max, name code goes here
}
fclose(file);

Here is a cool, simple tutorial on how to do that.
Please note that you'll need to adapt the example a little bit, but that should not be too difficult.
Also you could try to find a library that does the job, I'm sure there are a lot of such libraries for C :)

Use strtok():
#include <stdio.h>
#include <string.h>
int main() {
char input[] = "100;200;first";
char name[10];
int min, max;
char* result = NULL;
char delims[] = ";";
result = strtok(input, delims);
// atoi() converts ascii to integer.
min = atoi(result);
result = strtok(NULL, delims);
max = atoi(result);
result = strtok(NULL, delims);
strcpy(name, result);
printf("Min=%d, Max=%d, Name=%s\n", min, max, name);
}
Output:
Min=100, Max=200, Name=first

Related

How to parse textfile correctly?

I've got a text file containing a bunch of random data from programs I've written:
hdfs45 //the hdsf part stays the same everytime, but the number always changes
I'm trying to parse this line of data into two parts, the hdfs part and the 45 part (to be later converted to an int)
I've tried something along the lines of this:
Char * a, * b;
char str[100];
FILE* ptr;
ptr = fopen("test.txt","r"); // opens sucessfully
while(fgets(str,100,file))
{
a = strtok(str," \n");
printf("%s",a); // but this prints the whole string
}
The data will be random, for setting the delimiter to "45" is useless. However the first part "hdfs" is always the same,any help would be much appreciated.
If "hdfs" never changes, then you can simply convert the characters after the first 4 into a number, i.e.:
int num = atoi(str + 4);
str[4] = '\0';
In your example, num will equal 45, and str will equal hdfs.
You can't use strtok because there is nothing to tokenize (you can't use a delimiter), try:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char str[100] = "hdfs45";
char *ptr;
long num;
ptr = strpbrk(str, "012345679");
if (ptr) {
num = strtol(ptr, NULL, 10);
*ptr = '\0';
printf("%s -> %ld\n", str, num);
}
return 0;
}

C - Is this the right way to use strtok in the following situation

If i have a string that contains 10X15. And i want to separate the 10 and 15. Would the following code be correct. I am concerned about the second part of the code, is putting "NULL" there the right thing to do.
char * stringSixrows = strtok(stringSix[0], "X");
char * stringSixcollumns = strtok(NULL, "NULL");
//I put the second null there cause its the end of string, im not sure if its right though.
I'd say the "canonical" way to obtain the "pointer to the remaining string" is:
strtok(NULL, "")
strtok searches for any of the delimiters in the provided string, so if you don't provide any delimiters, it cannot find anything and thus only stops at the end of the input string.
example
#include <stdio.h>
#include <string.h>
int main(void){
char stringSix[] = "10X15";
char *stringSixrows = strtok(stringSix, "X");
char *stringSixcolumns = strtok(NULL, "X");
printf("%s, %s\n", stringSixrows, stringSixcolumns);
return 0;
}
another way
char stringSix[] = "10X15";
char stringSixrows[3];
char stringSixcolumns[3];
char *p;
if(NULL!=(p = strchr(stringSix, 'X')))
*p = '\0';
else {
printf("invalid format\n");
return -1;
}
strcpy(stringSixrows, stringSix);
strcpy(stringSixcolumns, p+1);
printf("%s, %s\n", stringSixrows, stringSixcolumns);
const char *stringSix = "10X15";
int stringSixrows;
int stringSixcolumns;
if(2==sscanf(stringSix, "%dX%d", &stringSixrows, &stringSixcolumns))
printf("%d, %d\n", stringSixrows, stringSixcolumns);
You can use strtol to convert the string to numbers as well as seek to the next string. Below code safely does the intended operation:
char stringSix[] = "10X15";
char * pEnd;
long firstNumber = strtol (stringSix,&pEnd, 10);
pEnd = strtok(pEnd, "");
long secondNumber = strtol (pEnd,&pEnd, 10);

Better understanding of strstr in C

I already asked on question earlier about the string function strstr, and it just turned out that I had made a stupid mistake. Now again i'm getting unexpected results and can't understand why this is. The code i've written is just a simple test code so that I can understand it better, which takes a text file with a list of 11 words and i'm trying to find where the first word is found within the rest of the words. All i've done is move the text document words into a 2D array of strings, and picked a few out that I know should return a correct value but are instead returning NULL. The first use of strstr returns the correct value but the last 3, which I know include the word chant inside of them, return NULL. If again this is just a stupid mistake I have made I apologize, but any help here on understanding this string function would be great.
The text file goes is formatted like this:
chant
enchant
enchanted
hello
enchanter
enchanting
house
enchantment
enchantress
truck
enchants
And the Code i've written is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE* file1;
char **array;
int i;
char string[12];
char *ptr;
array=(char **)malloc(11*sizeof(char*));
for (i=0;i<11;i++) {
array[i]=(char *)malloc(12*sizeof(char));
}
file1=fopen(argv[1],"r");
for (i=0;i<11;i++) {
fgets(string,12,file1);
strcpy(array[i],string);
}
ptr=strstr(array[1],array[0]);
printf("\nThe two strings chant and %s yield %s",array[1],ptr);
ptr=strstr(array[2],array[0]);
printf("\nThe two strings chant and %s yield %s",array[2],ptr);
ptr=strstr(array[4],array[0]);
printf("\nThe two strings chant and %s yield %s",array[4],ptr);
ptr=strstr(array[5],array[0]);
printf("\nThe two strings chant and %s yields %s",array[5],ptr);
return 0;
}
Get rid of the trailing \n after fgets().
for (i=0;i<11;i++) {
fgets(string, sizeof string, file1);
size_t len = strlen(string);
if (len > 0 && string[len-1] == '\n') string[--len] = '\0';
strcpy(array[i], string);
}
char *chomp(char *str){
char *p = strchr(str, '\n');
if(p)
*p = '\0';
return str;
}
...
strcpy(array[i], chomp(string));

How to extract a number from a string in C

I am working on a project for school but I can't figure out how I can extract the year from a date in a string "20-02-2015" the date is always of the form XX-XX-XXXX
Is there some way to use some kind of scan function?
char date[]="20-02-2015";
int d,m,y;
sscanf(date,"%d-%d-%d",&d,&m,&y);
Assuming that your string is given as char* str or as char str[], you can try this:
int day,mon,year;
sscanf(str,"%d-%d-%d",&day,&mon,&year);
Or you can try this, for a slightly better performance (by avoiding the call to sscanf):
int year = 1000*(str[6]-'0')+100*(str[7]-'0')+10*(str[8]-'0')+(str[9]-'0');
You can use the strtok() function to split a string (and specify the delimiter to use)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *date = malloc(10);
char *day = NULL;
char *month = NULL;
char *year = NULL;
strcpy(date, "01-03-2014");
day = strtok(date, "-");
printf("%s\n",day);
month = strtok(NULL, "-");
printf("%s\n",month);
year = strtok(NULL, "-");
printf("%s\n",year);
free(date);
return 0;
}
the output :
01
03
2014
Yes, with the %d-%d-%d format.
If reading from STDIN, use scanf, from a file use fscanf and from a string use sscanf
you can divide the string using strtok(date,"-") then can use atoi() to get the date, month and year as numbers. check this link it can help you
As other have suggested "%d-%d-%d".
To add error checking, should code need to insure no trailing garbage and all was there:
char date[80];
fgets(data, sizeof date, stdin);
int d,m,y;
in n;
int cnt = sscanf(date, "%d-%d-%d%n", &d, &m, &y, &n);
if (cnt == 3 && date[n] == '\n') Good();
else Bad();

Find int in a string (char*) in pure c

There is a string with a line of text. Let's say:
char * line = "Foo|bar|Baz|23|25|27";
I would have to find the numbers.
I was thinking of something like this:
If the given char is a number, let's put it into a temporary char array. (buffer)
If the next character is NOT a number, let's make the buffer a new int.
The problem is... how do I find numbers in a string like this?
(I'm not familiar with C99/gcc that much.)
Compiler used: gcc 4.3 (Environment is a Debian Linux stable.)
I would approach as the following:
Considering '|' as the separator, tokenize the line of text, i.e. split the line into multiple fields.
For each token:
If the token is numeric:
Convert the token to a number
Some library functions that might be useful are strtok, isdigit, atoi.
One possible implementation for the approach suggested in this answer, based on sscanf.
#include <stdio.h>
#include <string.h>
void find_integers(const char* p) {
size_t s = strlen(p)+1;
char buf[s];
const char * p_end = p+s;
int n;
/* tokenize string */
for (; p < p_end && sscanf(p, "%[^|]%n", &buf, &n); p += (n+1))
{
int x;
/* try to parse an integer */
if (sscanf(buf, "%d", &x)) {
printf("got int :) %d\n", x);
}
else {
printf("got str :( %s\n", buf);
}
}
}
int main() {
const char * line = "Foo|bar|Baz|23|25|27";
find_integers(line);
}
Output:
$ gcc test.c && ./a.out
got str :( Foo
got str :( bar
got str :( Baz
got int :) 23
got int :) 25
got int :) 27

Resources