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();
Related
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);
I'm new to C language and I need a help on String functions.
I have a string variable called mcname upon which I would like to compare the characters between special characters.
For example:
*mcname="G2-99-77"
I expect the output to be 99 as this is between the - characters.
How can I do this in C please?
Travel the string (walking pointer) till u hit a special character.
Then start copying the characters into seperate array untill u hit the next special character (Place a null character when u encounter the special character second time)
You can do this by using strtok or sscanf
using sscanf:
#include <stdio.h>
int main()
{
char str[64];
int out;
char mcname[] = "G2-99-77";
sscanf(mcname, "%[^-]-%d", str, &out);
printf("%d\n", out);
return 0;
}
Using strtok:
#include <stdio.h>
#include <string.h>
int main()
{
char *str;
int out;
char mcname[] = "G2-99-77";
str = strtok(mcname, "-");
str = strtok (NULL, "-");
out = atoi(str);
printf("%d\n", out);
return 0;
}
sscanf() has great flexibility. Used correctly, code may readily parse a string.
Be sure to test the sscanf() return value.
%2[A-Z0-9] means to scan up to 2 characters from the set 'A' to 'Z' and '0' to '9'.
Use %2[^-] if code goal is any 2 char other than '-'.
char *mcname = "G2-99-77";
char prefix[3];
char middle[3];
char suffix[3];
int cnt = sscanf(mcname, "%2[A-Z0-9]-%2[A-Z0-9]-%2[A-Z0-9]", prefix, middle,
suffix);
if (cnt != 3) {
puts("Parse Error\n");
}
else {
printf("Prefix:<%s> Middle:<%s> Suffix:<%s>\n", prefix, middle, suffix);
}
I'm sorry for the sloppy title, but I didn't know how to format my question correctly. I'm trying to read a .txt, of which every line has information needed to fill a struct. First I use fgets to read the line, and then i was going to use sscanf to read the individual parts. Now here is where I'm stuck: normally sscanf breaks off parts on whitespaces, but I need the whitespace to be included. I know that sscanf allows ignoring whitespaces, but the tricky part is that I then need some other arbitrary character to separate the parts. For example, I have to break the line
Carl Sagan~Contact~scifi~1997
up into parts for Author,Name,Genre,year. You can see I need the space in Carl Sagan, but I need the function to break off the strings on the tilde character. Any help is appreciated
If your input is delimited by ~ or for instance any specific character:
Use this:
sscanf(s, "%[^~]", name);
[^ is conversion type, that matches all characters except the ones listed, ending with ]
Here is the sample program for testing it:
#include <stdio.h>
int main(int argv, char **argc)
{
char *s = "Carl Sagan~Contact~scifi~1997";
char name[100], contact[100], genre[100];
int yr;
sscanf(s, "%99[^~]~%99[^~]~%99[^~]~%d", name, contact, genre, &yr);
printf("%s\n%s\n%s\n%d\n", name, contact, genre, yr);
return 0;
}
You need strtok. Use ~ as your delimiter.
See the documentation: http://linux.die.net/man/3/strtok
strtok has some drawbacks but it sounds like it will work for you.
EDIT:
After reading this, it sounds like you can use sscanf cleverly to achieve the same result, and it may actually be safer after all.
#include <stddef.h>
#include <string.h>
#include <stdio.h>
char* mystrsep(char** input, const char* delim)
{
char* result = *input;
char* p;
p = (result != NULL) ? strpbrk(result, delim) : NULL;
if (p == NULL)
*input = NULL;
else
{
*p = '\0';
*input = p + 1;
}
return result;
}
int main()
{
char str[] = "Carl Sagan~Contact~scifi~1997";
const char delimiters[] = "~";
char* ptr;
char* token;
ptr = str;
token = mystrsep(&ptr, delimiters);
while(token)
{
printf("%s\n",token);
token = mystrsep(&ptr, delimiters);
}
return 0;
}
Output :-
Carl Sagan
Contact
scifi
1997
I'm trying to extract a string and an integer out of a string using sscanf:
#include<stdio.h>
int main()
{
char Command[20] = "command:3";
char Keyword[20];
int Context;
sscanf(Command, "%s:%d", Keyword, &Context);
printf("Keyword:%s\n",Keyword);
printf("Context:%d",Context);
getch();
return 0;
}
But this gives me the output:
Keyword:command:3
Context:1971293397
I'm expecting this ouput:
Keyword:command
Context:3
Why does sscanf behaves like this? Thanks in advance you for your help!
sscanf expects the %s tokens to be whitespace delimited (tab, space, newline), so you'd have to have a space between the string and the :
for an ugly looking hack you can try:
sscanf(Command, "%[^:]:%d", Keyword, &Context);
which will force the token to not match the colon.
If you aren't particular about using sscanf, you could always use strtok, since what you want is to tokenize your string.
char Command[20] = "command:3";
char* key;
int val;
key = strtok(Command, ":");
val = atoi(strtok(NULL, ":"));
printf("Keyword:%s\n",key);
printf("Context:%d\n",val);
This is much more readable, in my opinion.
use a %[ convention here. see the manual page of scanf: http://linux.die.net/man/3/scanf
#include <stdio.h>
int main()
{
char *s = "command:3";
char s1[0xff];
int d;
sscanf(s, "%[^:]:%d", s1, &d);
printf("here: %s:%d\n", s1, d);
return 0;
}
which gives "here:command:3" as its output.
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