I am trying to write a program that will take the following input and will format it and output it to a text file.
Here is a picture of how it should work
?mrgn left: Each line following the command will be indented left spaces from
the left-hand margin. Note that this indentation must be included in the page
width. If this command does not appear in the input file, then the value of left
is 0 (zero).
I did the following so far:
while (fgets(line, MAX_LINE_LEN-1, infile) != NULL){/*Read the first line if it is not empty*/
char last[MAX_WORD_LEN] = {0};
char *p;
for (p = strtok(line, " "); p; p = strtok(NULL, " ")){
if(*last && strcmp(last, width)==0){
iwidth = atoi(p);
printf("width = %d\n", iwidth);
}
if(*last && strcmp(last, margin)==0){
imargin = atoi(p);
printf("margin = %d\n", imargin);
}
strncpy (last, p, MAX_WORD_LEN);
if(iwidth != 0 || imargin != 0){
printf("%s ", p);
}else{
printf("%s", line);
}
}
}
I am able to store the value of width and margin to a variable. I am now stuck on how I can specify the required formatting. I did some research but I couldn't find what I want. Please help!
Thank you!
Cheers!
After you have had several hours to work on the problem, let me give you a few pointers (no pun intended) that may help simplify your approach to the problem. While you can certainly use strtok to parse your option and width from the input file, there really is no need to tokenize when you know the line format containing the option will be "?name value".
A simplified approach, knowing your file contains the option as the first line, would simply be to read the entire line (using fgets or POSIX getline), verify the first character is '?' and then parse the option name and value from the line with sscanf. (you can either include the '?' in your format-string, or simply begin the parse at the 2nd character. (my choice) To accomplish this you could start with something similar to:
#include <stdio.h>
#include <string.h> /* for strcmp, strlen */
#define OPT 32 /* if you need constants, #define one (or more) */
#define WDTH 78
#define MAXC 1024
void str_word_wrap (char *buf, int n); /* wrap function prototype */
int main (void) {
char buf[MAXC] = "", /* buffer to hold words in file */
*p = buf, /* pointer to buf */
opt[OPT] = ""; /* buffer to hold option found in file */
int width = WDTH, /* variable holding width from option */
used = 0, /* number of chars used in buf */
val = 0; /* temp value to read option value from file */
/* option on line 1, read entire line */
if (!fgets (buf, MAXC, stdin) || *buf != '?')
fputs ("error: unexpected file format, using default width.\n\n",
stderr);
/* parse option and value, compare option is "width", use val as width */
if (sscanf (buf + 1, "%s %d", opt, &val) == 2) {
if (strcmp (opt, "width") == 0)
width = val;
}
...
At this point in your code, buf contains the first line, opt contains the option name, and width contains the width specified in the file (or the default width WDTH (78) in the event the first line did not contain the "?width val" information). Ideally, if the first line was not a valid option/value line, you would simply eliminate the excess whitespace from buf, add an ending ' ' and continue, but that code is left to you.
(note: I just redirect the file to stdin so I read from stdin instead of a file here -- but your infile is fine as well. You would just substitute infile where I read stdin)
Since you simply want to eliminate all the additional whitespace from your input file leaving a normally formatted paragraph which you will wrap to the specified width, using fscanf with the "%s" format specifier can handle the whitespace removal automatically. (with the scanf family, "%s" and numeric format specifiers ignore leading whitespace, "%c" and "%[..]" do not). So reading the remainder of the file into your buffer is simply a matter of reading each word in the file, keeping track of how many characters in your buffer you have used (so you know the next word will fit), and adding a ' ' (space) between each word as you add them to your buffer.
You can use strcat if that helps, or you can simply use a pointer and write a ' ' at one past the end of the current buffer and then a nul-terminating character past that on each iteration. Either way, just keep track of how many characters you have used so far and the len (length) of what you are adding, and then update your used count with the length of each word as you go. You could do something like the following:
while (scanf ("%s", p + used) == 1) { /* read each word, ignore WS */
size_t len = strlen (p + used); /* get length of word */
if (used + len + 2 >= MAXC) { /* make sure it fits with ' ' */
fputs ("warning: file truncated.\n", stderr);
break; /* note you can refine to save 1-char space at end */
}
*(p + used + len++) = ' '; /* add space at end of word */
*(p + used + len) = 0; /* nul-termiante after space */
used += len; /* update used with len */
}
*(p + --used) = 0; /* overwrite final ' ' with nul-character */
At this point you could write out your width value and the contents of your filled buffer for a check before you wrap the lines to width. I simply write the width used out before outputting the wrapped lines which completes the main() function of the program, e.g.
printf ("Wrapping file at width: %d\n\n", width);
str_word_wrap (buf, width); /* wrap buffer at width chars/output */
return 0;
}
All that remains is finishing the function to wrap the buffer to no more that width characters per line as you output your buffer. I provided the prototype above for str_word_wrap function and details in my original comment concerning the approach to wrapping the buffer by simply using a sliding-window of width length to work down your buffer, outputting the words that fit within the sliding window each time it is moved down the buffer.
To accomplish the task you generally use three pointers (I name then p the pointer to the current char, sp the start pointer for the window, and ep the end pointer for the window. The scheme is this, you begin with all three initialized to the beginning of your buffer, you then iterate over each char with p until p points to a space between the words, setting the end-pointer ep = p; each time a space is encountered. On each iteration you check if p - sp >= width, where p - sp is simply the current pointer address minus the start pointer address which tells you how many characters you have moved from the start. If that equals or exceeds your width, you know you last set ep (your end-pointer) to the last whitespace in the windows marking the end of the last word to output.
All that remains is outputting the line up to the end-pointer, (and a '\n') and then setting your new start-pointer to the next character after end-pointer and you can set your end-pointer to one after the current pointer (which slides your window forward) and you repeat. Nothing fancy is needed. Something like the following works fine:
void str_word_wrap (char *buf, int n)
{
char *p = buf, /* pointer to current char */
*sp = buf, /* pointer to start of line to print */
*ep = buf; /* pointer to end of line to print */
for (; *p && *p != '\n'; p++) { /* loop over each char (omit '\n')*/
if (*p == ' ') /* if space, set ep */
ep = p;
if (p - sp >= n) { /* if wrap length 'n' reached */
while (sp < ep) /* loop outputting chars sp -> ep */
putchar (*sp++);
putchar ('\n'); /* tidy up with '\n' */
sp = ++ep; /* set start to next after end */
ep = ++p; /* set end to next after current */
}
}
while (*sp && *sp != '\n') /* output last line of chars */
putchar (*sp++);
putchar ('\n'); /* tidy up with final '\n' */
}
Putting that altogether will handle your case, exactly:
Example Input File
$ cat dat/taggedparagraph.txt
?width 30
While there are enough characters here to
fill
at least one line, there is
plenty
of
white space that needs to be
eliminated
from the original
text file.
Now simply running the program using the file as input or redirecting the file to the programs stdin gives:
Example Use/Output
$ ./bin/wrapped_tagged_p < dat/taggedparagraph.txt
Wrapping file at width: 30
While there are enough
characters here to fill at
least one line, there is
plenty of white space that
needs to be eliminated from
the original text file.
Look things over and let me know if you have questions. This all boils down to basic pointer arithmetic and keeping track of where you are within a buffer while iterating over each character in the buffer to extract whatever specific information you need from it. You will often hear that referred to as "walking-a-pointer" over or down the buffer. Using a sliding-window is nothing more than walking-a-pointer while keeping track of the fixed point you started from and limiting the walk to no more than some fixed width of characters, and doing whatever it is you need to over-and-over again until you reach the end.
Help "Learn About Pointers"
Since in your comment below your question you mentioned you were "going to learn about pointers", start with the basics:
A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int a = 5;, a pointer would simply hold the address where 5 is stored in memory, e.g. int *b = &a;.
To reference the value at the address held by a pointer you dereference the pointer by using the unary '*' character before the pointer name. E.g., b holds the address of a (e.g. b point to a), so to get the value at the address held by b, you simply dereference b, e.g. *b.
It works the same way regardless what type of object the pointer points to. It is able to work that way because the type of the pointer controls the pointer arithmetic, e.g. with a char * pointer, pointer+1 point to the next byte, for an int * pointer (normal 4-byte integer), pointer+1 will point to the next int at an offset 4-bytes after pointer. (so a pointer, is just a pointer.... where arithmetic is automatically handled by the type)
When you are dealing with strings in C, you can iterate from the beginning to the end of the string checking each character and stopping when you reach the nul-terminating character at the end of every string. This nul-character serves as a sentinel for the end of the string. You will see it represented as '\0' or just plain 0. Both are equivalent. The ASCII character '\0' has the integer value 0.
A simple example of walking a pointer may help cement the concept:
#include <stdio.h>
int main (void) {
char buf[] = "walk-a-pointer down buf", /* buffer */
*p = buf; /* initialize p to point to buffer */
/* dereference the pointer to get the character at that address */
while (*p) { /* while *p != 0, or (*p != '\0') */
putchar (*p); /* output each character */
p++; /* advance pointer to next char */
}
putchar ('\n'); /* then tidy up with a newline */
return 0;
}
Example Use/Output
$ ./bin/walkpointer
walk-a-pointer down buf
Related
I have c variable file_path -
"a/b/c/xx.xxx_LOB_xxxx.caseno_YYYYMMDD.seq_no.csv"
From this file_path variable, I want to get the value of file_name excluding path,LOB,caseno,file_date(YYYYMMDD) and seq_no using C language in different variables. I tried with strtok() but not able to get the values.
Can you suggest how will get the value of each variable?
Thank you.
You have several options to separate the string. (you always have several options for parsing strings in C) You can always use a pair of pointers to work your way down the input string, bracketing and copying any set of characters between the two pointers. (you can operate on a non-mutable string like a String Literal because the original isn't modified)
You can use strtok() to help break the original up into smaller parts (sometimes into exactly what you need). However in this case, since '_' can be both a delimiter as well as be an included character in what you extract, you would still need to manually parse what you need from the tokens separated by strtok(). (strtok() modifies the string it operates on, so it must be mutable)
A third option is to craft a format-string and use sscanf() to parse the variables from the input. Since your format is fixed -- you are in luck and you can simply use sscanf to separate what you need. If you are not intimately familiar with the sscanf format-string and all of the modifiers and conversion specifiers, then spend an hour reading, and understanding, man 3 scanf -- time spent will save you ten-fold hours later.
Your fixed format, assuming no one variable in the string can be greater that 127-characters (adjust as necessary), can be accommodated with the format string:
" %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]"
The string is separated into 4 strings. The parts of the string that are not needed are discarded using the assignment suppression operator the '*'. If you are separating the input into an array of strings arr, then you can write a simple function to handle the separation for you, e.g.
int varsfrompath (char (*arr)[MAXLEN], char *str)
{
int i = sscanf (str, " %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]",
arr[0], arr[1], arr[2], arr[3]);
return i == EOF ? 0 : i; /* return no. of vars separated */
}
Which returns the number of items successfully parsed from the string. (zero if an input failure occurs)
A working example would be:
#include <stdio.h>
#include <string.h>
#define NELEM 4
#define MAXLEN 128
int varsfrompath (char (*arr)[MAXLEN], char *str)
{
int i = sscanf (str, " %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]",
arr[0], arr[1], arr[2], arr[3]);
return i == EOF ? 0 : i; /* return no. of vars separated */
}
int main (void) {
char fname[] = "a/b/c/xx.xxx_LOB_xxxx.caseno_YYYYMMDD.seq_no.csv",
results[NELEM][MAXLEN] = { "" };
int n = varsfrompath (results, fname);
for (int i = 0; i < n; i++)
printf ("results[%2d] = '%s'\n", i, results[i]);
}
Example Use/Output
$ ./bin/varsfrompath
results[ 0] = 'LOB'
results[ 1] = 'caseno'
results[ 2] = 'YYYYMMDD'
results[ 3] = 'seq_no'
This is by far the simplest way to handle your fixed format. A manual parse with a pair of pointers is more involved from an accounting (for where you are in the string standpoint), but no more difficult. (tedious may be the word)
Look things over and if I misinterpreted your separation needs, let me know and I can adjust it.
Manual Parse Using a Pair of Pointers
If rather than spend time with the man 3 scanf man page, you would rather spend time with an 8.5x11 sheet of paper and pencil with your accounting hat on to do the same thing using a pair of pointers, then you could do something similar to the following.
You have a start pointer sp and end pointer ep and you simply work down your line of input to anchor the sp before the variable to extract, and the ep at the end of the variable and then use memcpy() to copy the characters between them. (you will have to adjust by 1 on occasion depending on whether you are pointing at the beginning of the variable you want, or once character before it to the delimiter. (the easy way to get your arithmetic right when working down the string is to only consider there being 1-char between the start and end pointers -- that way whether you need to add or subtract 1 to work around your delimiters will be clear)
You can replace the varsfrompath function above with the one that follows and receive the same results, e.g.:
int varsfrompath (char (*arr)[MAXLEN], const char *str)
{
char *sp, *ep; /* start pointer, end pointer */
int i = 0;
/* set sp to 1st '_' and ep to second '_', copy to arr and nul-terminate */
if (!(sp = strchr (str, '_')) || /* can't find 1st '_' */
!(ep = strchr (sp + 1, '_')) || /* can't find 2nd '_' */
ep - sp - 2 > MAXLEN) /* chars between -1 > MAXLEN */
return 0;
memcpy (arr[i], sp + 1, ep - sp - 1); /* copy ep - sp - 1 chars */
arr[i++][ep - sp - 1] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* set sp to next '.' and ep to next '_", copy to arr and nul-terminate */
if (!(sp = strchr (sp, '.')) || /* can't find next '.' */
!(ep = strchr (sp + 1, '_')) || /* can't find next '_' */
ep - sp - 2 > MAXLEN) /* chars between -1 > MAXLEN */
return i;
memcpy (arr[i], sp + 1, ep - sp - 1); /* copy ep - sp - 1 chars */
arr[i++][ep - sp - 1] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* set ep to next '.', copy to arr and nul-terminate */
if (!(ep = strchr (sp, '.')) || ep - sp - 2 > MAXLEN) /* no '.' or too long */
return i;
memcpy (arr[i], sp, ep - sp); /* copy ep - sp chars */
arr[i++][ep - sp] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* repeate exact same steps for last var */
if (!(ep = strchr (sp, '.')) || ep - sp - 2 > MAXLEN)
return i;
memcpy (arr[i], sp, ep - sp);
arr[i++][ep - sp] = 0;
sp = ++ep;
return i; /* return no. of vars separated */
}
It may look more complicated, but you are actually just using simple string functions like strchr() to position the pointers, and then just extracting the characters between them. Compare and contrast both approaches.
I am trying to write an if else statement that looks at a user input and then splits it after index[1] if the string includes the letter b or split after index[0] if the string input doesnt include the letter b. How would I approach that? Pretty new to C so not too sure.
This is what I have so far... I think im on the right path and am trying to figure out how I would finish it off so it does what I want it to do.
int split_note_and_chord(char* string, char* note, char* chord)
{
for(user input doesnt have b in it)
{
if(i = 0; i <index; i++)
{
note[i] = string[i];
}
note[index] = 0;
else{ if(i = 0; i < index; i++)
{
note[i] = strlen(string[2]);
}
}
}
C string is nothing but a char array
string.h provides handy functions to check the string contents
you can use if condition and strstr and strchr functions for your logic
For example
#include <stdio.h>
#include <string.h>
int main () {
const char *input = "backwards";
char *ret;
ret = strstr(input, "b");
if( ret != NULL ) {
} else {
}
}
The strstr will return NULL if the b does not exist
You can also use strchr if you want the second argument as single char strchr(input, 'b');
There are a number of ways to approach splitting your input string after the 2nd character if the input contains 'b' or after the 1st character otherwise. Since you are dealing with either a 1 or 2, all you need to do is determine if 'b' is present. The easiest way to do that is with strchr() which will search a given string for the first occurrence of a character, returning a pointer to that character if found, or NULL otherwise. See man 3 strchr
So you can use strchr to test if 'b' is present, if the return isn't NULL split the string after the 2nd character, if it is NULL, split it after the first.
A simple implementation using a ternary to set the split-after size for input read into a buffer buf would be:
char part2[MAXC]; /* buffer to hold 2nd part */
size_t split; /* number of chars to split */
/* if buf contains 'b', set split at 2, otherwise set at 1 */
split = strchr(buf, 'b') ? 2 : 1;
strcpy (part2, buf + split); /* copy part2 from buf */
buf[split] = 0; /* nul-terminate buf at split */
A quick implementation allowing you to enter as many strings as you like and it will split after the 1st or 2nd character depending on the absense, or presence of 'b' would be:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer to hold line of input */
fputs ("Enter a string to split (or [Enter] alone to exit)\n\n"
"string: ", stdout);
while (fgets (buf, MAXC, stdin)) { /* loop reading each line */
char part2[MAXC]; /* buffer to hold 2nd part */
size_t split; /* number of chars to split */
if (*buf == '\n') /* if [Enter] alone, exit */
break;
/* if buf contains 'b', set split at 2, otherwise set at 1 */
split = strchr(buf, 'b') ? 2 : 1;
strcpy (part2, buf + split); /* copy part2 from buf */
buf[split] = 0; /* nul-terminate buf at split */
printf (" part1: %s\n part2: %s\nstring: ", buf, part2);
}
}
(note: if you are unfamiliar with the ternary operator, it is simple (test) ? if_true : if_false. Above it is just shorthand for if (strchar (buf, 'b') != NULL) split = 2; else split = 1;)
Example Use/Output
$ ./bin/splitb
Enter a string to split (or [Enter] alone to exit)
string: look out
part1: l
part2: ook out
string: look out below
part1: lo
part2: ok out below
string:
Let me know if this is what you intended. If not, I'm happy to help further. Also, if you have any questions, just let me know.
Edit Based on Comment
It is still unclear what your list of notes are in your header file, but you can simply use a string constant to contain the letters of the notes, e.g.
#define NOTES "abcdefg" /* (that can be a string constant as well) */
(you can add upper case if needed or you can convert the input to lower -- whatever works for you)
If you simply need to find the first occurrence of one of the letters in the NOTES string, then strpbrk() will allow you to do just that returning a pointer to the first character of NOTES found in your string. (you must have some way to handle the user entering, e.g. "the note cflat", which would split on the first 'e' instead of 'c', but you will need to provide further specifics there)
Another consideration is how long note can be. If it is always 1-character, then you can simplify by just comparing against the first character in the string using strchr (NOTES, buf[0]) (which turns the way you normally think about using strchr() around -- using the fist string NOTES and the first char read from user input.
Taking a general approach that would break "---cflat---" into "---c" and "flat---", your function could be similar to:
int split_note_and_chord (char *string, char *note, char *chord)
{
char *p = strpbrk (string, NOTES); /* pointer to first of NOTES in string */
if (p != NULL) { /* if found */
strcpy (note, string); /* copy string to note */
note[p - string + 1] = 0; /* nul-terminate after note */
strcpy (chord, p + 1); /* copy rest to chord */
return 1; /* return success */
}
*note = 0; /* make note and chord empty-string */
*chord = 0;
return 0; /* return failure */
}
(note: if there is no char in NOTES found, then note and chord are made the empty-string by nul-terminating at the first character before returning zero to indication no-note found.)
A quick implementation similar to the first could be:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
#define NOTES "abcdefg" /* (that can be a string constant as well) */
int split_note_and_chord (char *string, char *note, char *chord)
{
...
}
int main (void) {
char buf[MAXC], /* buffer to hold line of input */
note[MAXC], /* buffer for node */
chord[MAXC]; /* buffer for chord */
fputs ("Enter a string with node and chord (or [Enter] alone to exit)\n\n"
"string: ", stdout);
/* loop reading each line until [Enter] alone */
while (fgets (buf, MAXC, stdin) && *buf != '\n') {
if (split_note_and_chord (buf, note, chord))
printf (" note : %s\n chord : %s\n", note, chord);
else
fputs ("\nerror: note not found in string.\n\n", stderr);
fputs ("string: ", stdout);
}
return 0;
}
(note: that using fgets() will read and include the '\n' resulting from the user pressing Enter in buf and thus it will also be included in the remainder copied to chord. You can use buf[strcspn (buf, "\n")] = 0; to trim it from buf -- or from chord by substituting chord for buf in the call using strcspn() as the index to nul-terminate at.)
(also note: you can adjust MAXC to fit your needs -- which is why you declare a constant in the first place -- to make it a simple change of one line at the top of your file)
Example Use/Output
Using your function to split various input would result in the following:
$ ./bin/splitb3
Enter a string with node and chord (or [Enter] alone to exit)
string: ---cflat---
note : ---c
chord : flat---
string: asharp
note : a
chord : sharp
string: bflat
note : b
chord : flat
string: hook
error: note not found in string.
string: c
note : c
chord :
There are many, many different way to do this and how to best approach it will depend on how you have your notes and chords defined in your header -- as well as what, if any, limitations you put on what format you require the user to enter. If you need more help, please edit your question and Add the contents of your header so we will know how they are declared and defined, as well as listing any constraints you want to place on what the user can enter.
I am trying to extract key, values from a text file, but I am having trouble determining how to locate the end of a value. Here is a short snippet of the text file.
GIRRAFE: A tall spotted animal
LION: A short carnivore.
Prince: The son of a king.
Princess: The daughter of a king.
This is my code:
FILE *fp;
char line[20], word[20];
int i = 0, endind;
fp = fopen(file, "r");
if (fp==NULL){
printf("Error parsing the file\n");
exit(1);
}
while (!feof(fp)){
fgets(line, 100, fp);
for (i;i<strlen(line);i++){
if (line[i]=='.'){
endind = i;
}
}
for (i;i<endind;i++){
word[i] = line[i];
printf("%s\n",word);
}
}
The code is not very good as Im not able to get a value ending with a complete blank newline.
From the sample data, it looks like the key ends at the first '.'
in the string. Use strchr(3) to find it. But it looks like
the value, and the whole item, ends with two newlines. For
that you will need to write code to read a paragraph into a string.
For that, malloc(3) and realloc(3) will be useful. If you have
a known maximum size, you can of course use a fixed size buffer.
Break the problem into parts. First, read a paragraph, then find
where the key ends, then find where the value starts. Decide if the
two newlines are part of the value, and whether the period is part
of the key.
To read a paragraph, read in a line. If the line is empty, which you can determine with strcmp(line, "\n") then you're done reading the value,
and you can move on. Otherwise, append the line to the paragraph buffer.
Once you've got a whole paragraph as a single string, find the end of the
key with char *keyend = strchr(para, '.'), which will return a pointer to the '.' character. You can replace that character with a null (*keyend = 0)
and now para is a string with the key. Next advance the keyend pointer
to the first non-whitespace character. There are several ways to do that. At this point, keyend will now point to the value. Which
gives you para as a pointer to the key, and keyend as a pointer to the
value. Having that, you can update your hash table.
I would also check for errors along the way, and probably use separate
variables better named for the paragraph, key, and value. Trimming
off the trailing newline and other data validation is optional. For example, what if a paragraph doesn't contain a '.' character at all?
You are on the right track. The simple way to determine if you have an empty line (in your case) is:
fgets(line, 100, fp);
if (*line == '\n')
// the line is empty
(note: if (line[0] == '\n') is equivalent. In each case you are simply checking whether the 1st char in line is '\n'. Index notation of line[x] is equivalent to pointer notation *(line + x), and since you are checking the 1st character, (e.g. x=0), pointer notation is simply *line)
While you are free to use strtok or any other means to locate the 1st '.', using strchr() or simply using a pointer to iterate (walk-down) the buffer until you find the first '.' is probably an easier way to go. Your parsing flow should look something like:
readdef = 0; // flag telling us if we are reading word or definition
offset = 0; // number of chars copied to definition buffer
read line {
if (empty line (e.g. '\n')) { // we have a full word + definition
add definition to your list
reset readdef flag = 0
reset offset = 0
}
else if (readdef == 0) { // line with word + 1st part of definiton
scan forward to 1st '.'
check number of chars will fit in word buffer
copy to word buffer (or add to your list, etc..)
scan forward to start of definition (skip punct & whitespace)
get length of remainder of line (so you can save offset to append)
overwrite \n with ' ' to append subsequent parts of definition
strcpy to defn (this is the 1st part of definition)
update offset with length
set readdef flag = 1
}
else { // we are reading additional lines of definition
get length of remainder of line (so you can save offset to append)
check number of chars will fit in definition buffer
snprintf to defn + offset (or you can use strcat)
update offset with length
}
}
add final defintion to list
The key is looping and handling the different states of your input (either empty-line -- we have a word + full definition, readdef = 0 we need to start a new word + definition, or readdef = 1 we are adding lines to the current definition) You can think of this as a state loop. You are simply handling the different conditions (or states) presented by your input file. Note -- you must add the final definition after your read-loop (you still have the last definition in your definition buffer when fgets returns EOF)
Below is a short example working with your data-file. It simply outputs the word/definition pairs -- where you would be adding them to your list. You can use any combination of strtok, strchr or walking a pointer as I do below to parse the data file into words and definitions. Remember, if you ever find a problem where you can't make strtok fit your data -- you can always walk a pointer down the buffer comparing each character as you go and responding as required to parse your data.
You can also use snprintf or strcat to add the multiple lines of definitions together (or simply a pointer and a loop), but avoid strncpy, especially for large buffers -- it has a few performance penalties as it zeros the unused space every time.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXW 128 /* max chars in word or phrase */
#define MAXC 1024 /* max char for read buffer and definition */
int main (int argc, char **argv) {
int readdef = 0; /* flag for reading definition */
size_t offset = 0, /* offset for each part of definition */
len = 0; /* length of each line */
char buf[MAXC] = "", /* read (line) buffer */
word[MAXW] = "", /* buffer storing word */
defn[MAXC] = ""; /* buffer storing definition */
/* open filename given as 1st argument, (or read stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line */
char *p = buf; /* pointer to parse word & 1st part of defn */
if (*buf == '\n') { /* empty-line, output definition */
defn[offset-1] = 0; /* remove trailing ' ' left for append */
printf ("defn: %s\n\n", defn);
readdef = 0; /* reset readdef flag - 0 */
offset = 0; /* reset offset - 0 */
}
else if (readdef == 0) { /* line contais word + 1st part of defn */
while (*p && *p != '.') /* find the first '.' */
p++;
if (p - buf + 1 > MAXW) { /* make sure word fits in word */
fprintf (stderr, "error: word exceeds %d chars.\n", MAXW - 1);
return 1;
}
snprintf (word, p - buf + 1, "%s", buf); /* copy to word */
printf ("word: %s\n", word); /* output word */
while (ispunct (*p) || isspace (*p)) /* scan to start of defn */
p++;
len = strlen (p); /* get length 1st part of defn */
if (len && p[len - 1] == '\n') /* chk \n, overwrite with ' ' */
p[len - 1] = ' ';
strcpy (defn, p); /* copy rest of line to defn */
offset += len; /* update offset (no. of chars in defn) */
readdef = 1; /* set readdef flag - 1 */
}
else { /* line contains next part of defn */
len = strlen (buf); /* get length */
if (len && buf[len - 1] == '\n') /* chk \n, overwite w/' ' */
buf[len - 1] = ' ';
if (offset + len + 1 > MAXC) { /* make sure it fits */
fprintf (stderr, "error: definition excees %d chars.\n",
MAXC - 1);
return 1;
}
snprintf (defn + offset, len + 1, "%s", buf); /* append defn */
offset += len; /* update offset */
}
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
defn[offset-1] = 0; /* remove trailing ' ' left for append */
printf ("defn: %s\n\n", defn); /* output final definition */
return 0;
}
Example Input File
$ cat dat/definitions.txt
ACTE. A peninsula; the term was particularly applied by the ancients to
the sea-coast around Mount Athos.
ACT OF COURT. The decision of the court or judge on the verdict, or the
overruling of the court on a point of law.
TELEGRAPH, TO. To convey intelligence to a distance, through the medium
of signals.
TELESCOPIC OBJECTS. All those which are not visible to the unassisted
eye.
TELL OFF, TO. To divide a body of men into divisions and subdivisions,
preparatory to a special service.
TELL-TALE. A compass hanging face downwards from the beams in the cabin,
showing the position of the vessel's head. Also, an index in front of
the wheel to show the position of the tiller.
Example Use/Output
$ /bin/read_def <dat/definitions.txt
word: ACTE
defn: A peninsula; the term was particularly applied by the ancients to the sea-coast around Mount Athos.
word: ACT OF COURT
defn: The decision of the court or judge on the verdict, or the overruling of the court on a point of law.
word: TELEGRAPH, TO
defn: To convey intelligence to a distance, through the medium of signals.
word: TELESCOPIC OBJECTS
defn: All those which are not visible to the unassisted eye.
word: TELL OFF, TO
defn: To divide a body of men into divisions and subdivisions, preparatory to a special service.
word: TELL-TALE
defn: A compass hanging face downwards from the beams in the cabin, showing the position of the vessel's head. Also, an index in front of the wheel to show the position of the tiller.
Look things over and let me know if you have further questions.
I want to check to make sure that a given string contained in an array called secretWord has no symbols in it (e.g. $ % & #). If it does have a symbol in it, I make the user re-enter the string. It takes advantage of recursion to keep asking until they enter a string that does not contain a symbol.
The only symbol I do accept is the NULL symbol (the symbol represented by the ASCII value of zero). This is because I fill all the empty space in the array with NULL symbols.
My function is as follows:
void checkForSymbols(char *array, int arraysize){ //Checks for symbols in the array and if there are any it recursively calls this function until it gets input without them.
for (int i = 0; i < arraysize; i++){
if (!isdigit(array[i]) && !isalpha(array[i]) && array[i] != (char) 0){
flushArray(array, arraysize);
printf("No symbols are allowed in the word. Please try again: ");
fgets(secretWord, sizeof(secretWord) - 1, stdin);
checkForSymbols(secretWord, sizeof(secretWord));
}//end if (!isdigit(array[i]) && !isalpha(array[i]) && array[i] != 0)
else
continue;
}//end for(i = 0; i < sizeof(string[]); i++){
}//end checkForSymbols
The problem: When I enter any input (see example below), the if statement runs (it prints No symbols are allowed in the word. Please try again: and asks for new input).
I assume the problem obviously stems from the statement if (!isdigit(array[i]) && !isalpha(array[i]) && array[i] != (char) 0). But I have tried changing the (char) 0 part to '\0' and 0 as well and neither change had any effect.
How do I compare if what is in the index is a symbol, then? Why are strings without symbols setting this if statement off?
And if any of you are wondering what the "flushArray" method I used was, here it is:
void flushArray(char *array, int arraysize){ //Fills in the entire passed array with NULL characters
for (int i = 0; i < arraysize; i++){
array[i] = 0;
}
}//end flushArray
This function is called on the third line of my main() method, right after a print statement on the first line that asks users to input a word, and an fgets() statement on the second line that gets the input that this checkForSymbols function is used on.
As per request, an example would be if I input "Hello" as the secretWord string. The program then runs the function on it, and the if statement is for some reason triggered, causing it to
Replace all values stored in the secretWord array with the ASCII value of 0. (AKA NULL)
Prints No symbols are allowed in the word. Please try again: to the console.
Waits for new input that it will store in the secretWord array.
Calls the checkForSymbols() method on these new values stored in secretWord.
And no matter what you input as new secretWord, the checkForSymbols() method's if statement fires and it repeats steps 1 - 4 all over again.
Thank you for being patient and understanding with your help!
You can do something like this to find symbols in your code, put the code at proper location
#include <stdio.h>
#include <string.h>
int main () {
char invalids[] = "#.<#>";
char * temp;
temp=strchr(invalids,'s');//is s an invalid character?
if (temp!=NULL) {
printf ("Invalid character");
} else {
printf("Valid character");
}
return 0;
}
This will check if s is valid entry or not similarly for you can create an array and do something like this if array is not null terminated.
#include <string.h>
char false[] = { '#', '#', '&', '$', '<' }; // note last element isn't '\0'
if (memchr(false, 'a', sizeof(false)){
// do stuff
}
memchr is used if your array is not null terminated.
As suggested by #David C. Rankin you can also use strpbrk like
#include <stdio.h>
#include <string.h>
int main () {
const char str1[] = ",*##_$&+.!";
const char str2[] = "##"; //input string
char *ret;
ret = strpbrk(str1, str2);
if(ret) {
printf("First matching character: %c\n", *ret);
} else {
printf("Continue");
}
return(0);
}
The only symbol I do accept is the NULL symbol (the symbol represented by the ASCII value of zero). This is because I fill all the empty space in the array with NULL symbols.
NULL is a pointer; if you want a character value 0, you should use 0 or '\0'. I assume you're using memset or strncpy to ensure the trailing bytes are zero? Nope... What a shame, your MCVE could be so much shorter (and complete). :(
void checkForSymbols(char *array, int arraysize){
/* ... */
if (!isdigit(array[i]) && !isalpha(array[i]) /* ... */
As per section 7.4p1 of the C standard, ...
In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.
Not all char values are representable as an unsigned char or equal to EOF, and so it's possible (and highly likely given the nature of this question) that the code above invokes undefined behaviour.
As you haven't completed your question (by providing an MCVE, and describing what errors are occuring) I'm assuming that the question you're trying to ask might be a duplicate of this question, this question, this question, this question and probably a whole lot of others... If so, did you try Googling the error message? That's probably the first thing you should've done. Should that fail in the future, ask a question about the error message!
As per request, an example would be if I input "Hello" as the secretWord string.
I assume secretWord is declared as char secretWord[] = "Hello"; in your example, and not char *secretWord = "Hello";. The two types are distinct, and your book should clarify that. If not, which book are you reading? I can probably recommend a better book, if you'd like.
Any attempt to modify a string literal (i.e. char *array = "Hello"; flushArray(array, ...)) is undefined behaviour, as explained by answers to this question (among many others, I'm sure).
It seems a solution to this problem might be available by using something like this...
In response to your comment, you are probably making it a bit tougher on yourself than it needs to be. You have two issues to deal with (one you are not seeing). The first being to check the input to validate only a-zA-Z0-9 are entered. (you know that). The second being you need to identify and remove the trailing '\n' read and included in your input by fgets. (that one may be tripping you up)
You don't show how the initial array is filled, but given your use of fgets on secretWord[1], I suspect you are also using fgets for array. Which is exactly what you should be using. However, you need to remove the '\n' included at the end of the buffer filled by fgets before you call checkforsymbols. Otherwise you have character 0xa (the '\n') at the end, which, of course, is not a-zA-Z0-9 and will cause your check to fail.
To remove the trailing '\n', all you need to do is check the last character in your buffer. If it is a '\n', then simply overwrite it with the nul-terminating character (either 0 or the equivalent character representation '\0' -- your choice). You simply need the length of the string (which you get with strlen from string.h) and then check if (string[len - 1] == '\n'). For example:
size_t len = strlen (str); /* get length of str */
if (str[len - 1] == '\n') /* check for trailing '\n' */
str[--len] = 0; /* overwrite with nul-byte */
A third issue, important, but not directly related to the comparison, is to always choose a type for your function that will return an indication of Success/Failure as needed. In your case the choice of void gives you nothing to check to determine whether there were any symbols found or not. You can choose any type you like int, char, char *, etc.. All will allow the return of a value to gauge success or failure. For testing strings, the normal choice is char *, returning a valid pointer on success or NULL on failure.
A fourth issue when taking input is you always need to handle the case where the user chooses to cancel input by generating a manual EOF with either ctrl+d on Linux or ctrl+z on windoze. The return of NULL by fgets gives you that ability. But with it (and every other input function), you have to check the return and make use of the return information in order to validate the user input. Simply check whether fgets returns NULL on your request for input, e.g.
if (!fgets (str, MAXS, stdin)) { /* read/validate input */
fprintf (stderr, "EOF received -> user canceled input.\n");
return 1; /* change as needed */
}
For your specific case where you only want a-zA-Z0-9, all you need to do is iterate down the string the user entered, checking each character to make sure it is a-zA-Z0-9 and return failure if anything else is encountered. This is made easy given that every string in C is nul-terminated. So you simply assign a pointer to the start of your string (e.g. char *p = str;) and then use either a for or while loop to check each character, e.g.
for (; *p != 0; p++) { do stuff }
that can be written in shorthand:
for (; *p; p++) { do stuff }
or use while:
while (*p) { do stuff; p++; }
Putting all of those pieces together, you could write your function to take a string as its only parameter and return NULL if a symbol is encountered, or return a pointer to your original string on success, e.g.
char *checkforsymbols (char *s)
{
if (!s || !*s) return NULL; /* validate string and not empty */
char *p = s; /* pointer to iterate over string */
for (; *p; p++) /* for each char in s */
if ((*p < 'a' || *p > 'z') && /* char is not a-z */
(*p < 'A' || *p > 'Z') && /* char is not A-Z */
(*p < '0' || *p > '9')) { /* char is not 0-9 */
fprintf (stderr, "error: '%c' not allowed in input.\n", *p);
return NULL; /* indicate failure */
}
return s; /* indicate success */
}
A short complete test routine could be:
#include <stdio.h>
#include <string.h>
#define MAXS 256
char *checkforsymbols (char *s);
int main (void) {
char str[MAXS] = "";
size_t len = 0;
for (;;) { /* loop until str w/o symbols */
printf (" enter string: "); /* prompt for user input */
if (!fgets (str, MAXS, stdin)) { /* read/validate input */
fprintf (stderr, "EOF received -> user canceled input.\n");
return 1;
}
len = strlen (str); /* get length of str */
if (str[len - 1] == '\n') /* check for trailing '\n' */
str[--len] = 0; /* overwrite with nul-byte */
if (checkforsymbols (str)) /* check for symbols */
break;
}
printf (" valid str: '%s'\n", str);
return 0;
}
char *checkforsymbols (char *s)
{
if (!s || !*s) return NULL; /* validate string and not empty */
char *p = s; /* pointer to iterate over string */
for (; *p; p++) /* for each char in s */
if ((*p < 'a' || *p > 'z') && /* char is not a-z */
(*p < 'A' || *p > 'Z') && /* char is not A-Z */
(*p < '0' || *p > '9')) { /* char is not 0-9 */
fprintf (stderr, "error: '%c' not allowed in input.\n", *p);
return NULL; /* indicate failure */
}
return s; /* indicate success */
}
Example Use/Output
$ ./bin/str_chksym
enter string: mydoghas$20worthoffleas
error: '$' not allowed in input.
enter string: Baddog!
error: '!' not allowed in input.
enter string: Okheisagood10yearolddog
valid str: 'Okheisagood10yearolddog'
or if the user cancels user input:
$ ./bin/str_chksym
enter string: EOF received -> user canceled input.
footnote 1.
C generally prefers the use of all lower-case variable names, while reserving all upper-case for macros and defines. Leave MixedCase or camelCase variable names for C++ and java. However, since this is a matter of style, this is completely up to you.
So I have a wall of text in a file and I need to recognize some words that are between the $ sign and call them as numbers then print the modified text in another file along with what the numbers correspond to.
Also lines are not defined and columns should be max 80 characters.
Ex:
I $like$ cats.
I [1] cats.
[1] --> like
That's what I did:
#include <stdio.h>
#include <stdlib.h>
#define N 80
#define MAX 9999
int main()
{
FILE *fp;
int i=0,count=0;
char matr[MAX][N];
if((fp = fopen("text.txt","r")) == NULL){
printf("Error.");
exit(EXIT_FAILURE);
}
while((fscanf(fp,"%s",matr[i])) != EOF){
printf("%s ",matr[i]);
if(matr[i] == '\0')
printf("\n");
//I was thinking maybe to find two $ but Idk how to replace the entire word
/*
if(matr[i] == '$')
count++;
if(count == 2){
...code...
}
*/
i++;
}
fclose(fp);
return 0;
}
My problem is that fscanf doesn't recognize '\0' so it doesn't go in the next line when I print the array..also I don't know how to replace $word$ with a number.
Not only will fscanf("%s") read one whitespace-delimited string at a time, it will also eat all whitespace between those strings, including line terminators. If you want to reproduce the input whitespace in the output, as your example suggests you do, then you need a different approach.
Also lines are not defined and columns should be max 80 characters.
I take that to mean the number of lines is not known in advance, and that it is acceptable to assume that no line will contain more than 80 characters (not counting any line terminator).
When you say
My problem is that fscanf doesn't recognize '\0' so it doesn't go in the next line when I print the array
I suppose you're talking about this code:
char matr[MAX][N];
/* ... */
if(matr[i] == '\0')
Given that declaration for matr, the given condition will always evaluate to false, regardless of any other consideration. fscanf() does not factor in at all. The type of matr[i] is char[N], an array of N elements of type char. That evaluates to a pointer to the first element of the array, which pointer will never be NULL. It looks like you're trying to determine when to write a newline, but nothing remotely resembling this approach can do that.
I suggest you start by taking #Barmar's advice to read line-by-line via fgets(). That might look like so:
char line[N+2]; /* N + 2 leaves space for both newline and string terminator */
if (fgets(line, sizeof(line), fp) != NULL) {
/* one line read; handle it ... */
} else {
/* handle end-of-file or I/O error */
}
Then for each line you read, parse out the "$word$" tokens by whatever means you like, and output the needed results (everything but the $-delimited tokens verbatim; the bracket substitution number for each token). Of course, you'll need to memorialize the substitution tokens for later output. Remember to make copies of those, as the buffer will be overwritten on each read (if done as I suggest above).
fscanf() does recognize '\0', under select circumstances, but that is not the issue here.
Code needs to detect '\n'. fscanf(fp,"%s"... will not do that. The first thing "%s" directs is to consume (and not save) any leading white-space including '\n'. Read a line of text with fgets().
Simple read 1 line at a time. Then march down the buffer looking for words.
Following uses "%n" to track how far in the buffer scanning stopped.
// more room for \n \0
#define BUF_SIZE (N + 1 + 1)
char buffer[BUF_SIZE];
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
char *p = buffer;
char word[sizeof buffer];
int n;
while (sscanf(p, "%s%n", word, &n) == 1) {
// do something with word
if (strcmp(word, "$zero$") == 0) fputs("0", stdout);
else if (strcmp(word, "$one$") == 0) fputs("1", stdout);
else fputs(word, stdout);
fputc(' ', stdout);
p += n;
}
fputc('\n', stdout);
}
Use fread() to read the file contents to a char[] buffer. Then iterate through this buffer and whenever you find a $ you perform a strncmp to detect with which value to replace it (keep in mind, that there is a 2nd $ at the end of the word). To replace $word$ with a number you need to either shrink or extend the buffer at the position of the word - this depends on the string size of the number in ascii format (look solutions up on google, normally you should be able to use memmove). Then you can write the number to the cave, that arose from extending the buffer (just overwrite the $word$ aswell).
Then write the buffer to the file, overwriting all its previous contents.