How to check if an index contains a symbol? - c

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.

Related

Specific case of c scanf()

Input : [1,3,2,4]
I want to make arr[4] = {1, 3, 2, 4} from this input using scanf(). How can I do this in C language?
It is possible to parse input such as you describe with scanf, but each scanf call will parse up to a maximum number of fields determined by the given format. Thus, to parse an arbitrary number of fields requires an arbitrary number of scanf calls.
In comments, you wrote that
I want to find a method to ignore '[', ']', ',' and only accept integer units.
Taking that as the focus of the question, and therefore ignoring the issues of how you allocate space for the integers to be read when you do not know in advance how many there will be, and assuming that you may not use input functions other than scanf, it seems like you are looking for something along these lines:
int value;
char delim[2] = { 0 };
// Scan and confirm the opening '['
value = 0;
if (scanf("[%n", &value) == EOF) {
// handle end of file or I/O error ...
} else if (value == 0) {
// handle input not starting with a '[' ...
// Note: value == zero because we set it so, and the %n directive went unprocessed
} else {
// if value != 0 then it's because a '[' was scanned and the %n was processed
assert(value == 1);
}
// scan the list items
do {
// One integer plus trailing delimiter, either ',' or ']'
switch(scanf("%d%1[],]", &value, delim)) {
case EOF:
// handle end of file or I/O error (before an integer is read) ...
break;
case 0:
// handle input not starting with an integer ...
// The input may be malformed, but this point will also be reached for an empty list
break;
case 1:
// handle malformed input starting with an integer (which has been scanned) ...
break;
case 2:
// handle valid (to this point) input. The scanned value needs to be stored somewhere ...
break;
default:
// cannot happen
assert(0);
}
// *delim contains the trailing delimiter that was scanned
} while (*delim == ',');
// assuming normal termination of the loop:
assert(*delim == ']');
Points to note:
it is essential to pay attention to the return value of scanf. Failure to do so and to respond appropriately will cause all manner of problems when unexpected input is presented.
the above will accept slightly more general input than you describe, with whitespace (including line terminators) permitted before each integer.
The directive %1[],] attempts to scan a 1-character string whose element is either ] or ,. This is a bit arcane. Also, because the input is scanned as a string, you must be sure to provide space for a string terminator to be written, too.
it would be easier to write a character-by-character parser for your specific format that does not rely on scanf. You could also use scanf to read one character at a time to feed such a parser, but that seems to violate the spirit of the exercise.
While I think that John Bollinger answer is pretty good and complete (even without considering the wonderful %1[[,]), I would go for a more compact and tolerant version like this:
#include <stdio.h>
size_t arr_input(int *arr, size_t max_size)
{
size_t n;
for (n = 0; n < max_size; ++n) {
char c;
int res = scanf("%c%d", &c, arr + n);
if (res != 2
|| (n == 0 && c != '[')
|| (n > 0 && c != ',')
|| (n > 0 && c == ']')) {
break;
}
}
return n;
}
int main(void)
{
char *test_strings[] = { "[1,2,3,4]", "[42]", "[1,1,2,3,5,8]", "[]",
"[10,20,30,40,50,60,70,80,90,100]", "[1,2,3]4" };
size_t test_strings_n = sizeof test_strings / sizeof *test_strings;
char filename[L_tmpnam];
tmpnam(filename);
for (size_t i = 0; i < test_strings_n; ++i) {
freopen(filename, "w+", stdin);
fputs(test_strings[i], stdin);
rewind(stdin);
int arr[9];
size_t num_elem = arr_input(arr, 9);
printf("%zu: %s -> ", i, test_strings[i]);
for (size_t j = 0; j < num_elem; ++j) {
printf("%d ", arr[j]);
}
printf("\n");
fclose(stdin);
}
remove(filename);
return 0;
}
The idea is that you allocate space for the maximum number of integers you accept, then ask the arr_input() function to fill it up to max_size elements.
The check after scanf() tries to cope with incorrect input, but is not very complete. If you trust your input to be correct (don't) you can even make it shorter, by dropping the three || cases.
The most complex thing was to write the test driver with tmp files, strings, reopening and such. Here I'd have loved to have std::istream to just drop a std::stringstream. The fact that the FILE interface doesn't support strings really bugs me.
int arr[4];
for(int i=0;i<4;i++) scanf("%d",&arr[i]);
Are you asking for this? I was little bit confused with your question, if this doesn't solve your query, then don't hesitate to ask again...
use scanf to read a string input from user then parse that input into an integer array
To parse you can use string function "find" to locate the "," and "[]" and then use "atoi" to convert string into integer to fill the destination input array.
Edit: find is a C++ function.
the C function is strchr

split a user inputed string at a specific letter in c

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.

How to sscanf only the last word from a string? [duplicate]

how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
char str[80];
str = "my cat is yellow";
How would I get yellow?
Something like this:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
In case you don't want to use 'strrchr' function, Here is the solution.
i = 0;
char *last_word;
while (str[i] != '\0')
{
if (str[i] <= 32 && str[i + 1] > 32)
last_word = &str[i + 1];
i++;
}
i = 0;
while (last_word && last_word[i] > 32)
{
write(1, &last_word[i], 1);
i++;
}
I would use function strrchr()
The best way to do this is to take advantage of existing solutions. One such solution (to a much more general problem) is Perl Compatible Regular Expressions, an open-source regular expression library for C. So, you can match the string "my cat is yellow" with the regular expression \b(\w+)$ (expressed in C as "\b(\w+)$") and keep the first captured group, which is "yellow."
(heavy sigh) The original code is WRONG in standard / K&R / ANSI C! It does NOT initialize the string (the character array named str)! I'd be surprised if the example compiled. What your program segment really needs is
if strcpy(str, "my cat is yellow")
{
/* everything went well, or at least one or more characters were copied. */
}
or, if you promised not to try to manipulate the string, you could use a char pointer to the hard-coded "my cat is yellow" string in your source code.
If, as stated, a "word" is bounded by a space character or a NULL character, then it would be faster to declare a character pointer and walk backwards from the character just before the NULL. Obviously, you'd first have to be sure that there was a non-empty string....
#define NO_SPACE 20
#define ZERO_LENGTH -1
int iLen;
char *cPtr;
if (iLen=strlen(str) ) /* get the number of characters in the sting */
{ /* there is at least one character in the string */
cPtr = (char *)(str + iLen); /* point to the NULL ending the string */
cPtr--; /* back up one character */
while (cPtr != str)
{ /* make sure there IS a space in the string
and that we don't walk too far back! */
if (' ' == *cPtr)
{ /* found a space */
/* Notice that we put the constant on the left?
That's insurance; the compiler would complain if we'd typed = instead of ==
*/
break;
}
cPtr--; /* walk back toward the beginning of the string */
}
if (cPtr != str)
{ /* found a space */
/* display the word and exit with the success code */
printf("The word is '%s'.\n", cPtr + 1);
exit (0);
}
else
{ /* oops. no space found in the string */
/* complain and exit with an error code */
fprintf(STDERR, "No space found.\n");
exit (NO_SPACE);
}
}
else
{ /* zero-length string. complain and exit with an error code. */
fprintf(STDERR, "Empty string.\n");
exit (ZERO_LENGTH);
}
Now you could argue that any non-alphabetic character should mark a word boundary, such as "Dogs-chase-cats" or "my cat:yellow". In that case, it'd be easy to say
if (!isalpha(*cPtr) )
in the loop instead of looking for just a space....

Dynamically allocate user inputted string

I am trying to write a function that does the following things:
Start an input loop, printing '> ' each iteration.
Take whatever the user enters (unknown length) and read it into a character array, dynamically allocating the size of the array if necessary. The user-entered line will end at a newline character.
Add a null byte, '\0', to the end of the character array.
Loop terminates when the user enters a blank line: '\n'
This is what I've currently written:
void input_loop(){
char *str = NULL;
printf("> ");
while(printf("> ") && scanf("%a[^\n]%*c",&input) == 1){
/*Add null byte to the end of str*/
/*Do stuff to input, including traversing until the null byte is reached*/
free(str);
str = NULL;
}
free(str);
str = NULL;
}
Now, I'm not too sure how to go about adding the null byte to the end of the string. I was thinking something like this:
last_index = strlen(str);
str[last_index] = '\0';
But I'm not too sure if that would work though. I can't test if it would work because I'm encountering this error when I try to compile my code:
warning: ISO C does not support the 'a' scanf flag [-Wformat=]
So what can I do to make my code work?
EDIT: changing scanf("%a[^\n]%*c",&input) == 1 to scanf("%as[^\n]%*c",&input) == 1 gives me the same error.
First of all, scanf format strings do not use regular expressions, so I don't think something close to what you want will work. As for the error you get, according to my trusty manual, the %a conversion flag is for floating point numbers, but it only works on C99 (and your compiler is probably configured for C90)
But then you have a bigger problem. scanf expects that you pass it a previously allocated empty buffer for it to fill in with the read input. It does not malloc the sctring for you so your attempts at initializing str to NULL and the corresponding frees will not work with scanf.
The simplest thing you can do is to give up on n arbritrary length strings. Create a large buffer and forbid inputs that are longer than that.
You can then use the fgets function to populate your buffer. To check if it managed to read the full line, check if your string ends with a "\n".
char str[256+1];
while(true){
printf("> ");
if(!fgets(str, sizeof str, stdin)){
//error or end of file
break;
}
size_t len = strlen(str);
if(len + 1 == sizeof str){
//user typed something too long
exit(1);
}
printf("user typed %s", str);
}
Another alternative is you can use a nonstandard library function. For example, in Linux there is the getline function that reads a full line of input using malloc behind the scenes.
No error checking, don't forget to free the pointer when you're done with it. If you use this code to read enormous lines, you deserve all the pain it will bring you.
#include <stdio.h>
#include <stdlib.h>
char *readInfiniteString() {
int l = 256;
char *buf = malloc(l);
int p = 0;
char ch;
ch = getchar();
while(ch != '\n') {
buf[p++] = ch;
if (p == l) {
l += 256;
buf = realloc(buf, l);
}
ch = getchar();
}
buf[p] = '\0';
return buf;
}
int main(int argc, char *argv[]) {
printf("> ");
char *buf = readInfiniteString();
printf("%s\n", buf);
free(buf);
}
If you are on a POSIX system such as Linux, you should have access to getline. It can be made to behave like fgets, but if you start with a null pointer and a zero length, it will take care of memory allocation for you.
You can use in in a loop like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // for strcmp
int main(void)
{
char *line = NULL;
size_t nline = 0;
for (;;) {
ptrdiff_t n;
printf("> ");
// read line, allocating as necessary
n = getline(&line, &nline, stdin);
if (n < 0) break;
// remove trailing newline
if (n && line[n - 1] == '\n') line[n - 1] = '\0';
// do stuff
printf("'%s'\n", line);
if (strcmp("quit", line) == 0) break;
}
free(line);
printf("\nBye\n");
return 0;
}
The passed pointer and the length value must be consistent, so that getline can reallocate memory as required. (That means that you shouldn't change nline or the pointer line in the loop.) If the line fits, the same buffer is used in each pass through the loop, so that you have to free the line string only once, when you're done reading.
Some have mentioned that scanf is probably unsuitable for this purpose. I wouldn't suggest using fgets, either. Though it is slightly more suitable, there are problems that seem difficult to avoid, at least at first. Few C programmers manage to use fgets right the first time without reading the fgets manual in full. The parts most people manage to neglect entirely are:
what happens when the line is too large, and
what happens when EOF or an error is encountered.
The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.
Upon successful completion, fgets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer...
I don't feel I need to stress the importance of checking the return value too much, so I won't mention it again. Suffice to say, if your program doesn't check the return value your program won't know when EOF or an error occurs; your program will probably be caught in an infinite loop.
When no '\n' is present, the remaining bytes of the line are yet to have been read. Thus, fgets will always parse the line at least once, internally. When you introduce extra logic, to check for a '\n', to that, you're parsing the data a second time.
This allows you to realloc the storage and call fgets again if you want to dynamically resize the storage, or discard the remainder of the line (warning the user of the truncation is a good idea), perhaps using something like fscanf(file, "%*[^\n]");.
hugomg mentioned using multiplication in the dynamic resize code to avoid quadratic runtime problems. Along this line, it would be a good idea to avoid parsing the same data over and over each iteration (thus introducing further quadratic runtime problems). This can be achieved by storing the number of bytes you've read (and parsed) somewhere. For example:
char *get_dynamic_line(FILE *f) {
size_t bytes_read = 0;
char *bytes = NULL, *temp;
do {
size_t alloc_size = bytes_read * 2 + 1;
temp = realloc(bytes, alloc_size);
if (temp == NULL) {
free(bytes);
return NULL;
}
bytes = temp;
temp = fgets(bytes + bytes_read, alloc_size - bytes_read, f); /* Parsing data the first time */
bytes_read += strcspn(bytes + bytes_read, "\n"); /* Parsing data the second time */
} while (temp && bytes[bytes_read] != '\n');
bytes[bytes_read] = '\0';
return bytes;
}
Those who do manage to read the manual and come up with something correct (like this) may soon realise the complexity of an fgets solution is at least twice as poor as the same solution using fgetc. We can avoid parsing data the second time by using fgetc, so using fgetc might seem most appropriate. Alas most C programmers also manage to use fgetc incorrectly when neglecting the fgetc manual.
The most important detail is to realise that fgetc returns an int, not a char. It may return typically one of 256 distinct values, between 0 and UCHAR_MAX (inclusive). It may otherwise return EOF, meaning there are typically 257 distinct values that fgetc (or consequently, getchar) may return. Trying to store those values into a char or unsigned char results in loss of information, specifically the error modes. (Of course, this typical value of 257 will change if CHAR_BIT is greater than 8, and consequently UCHAR_MAX is greater than 255)
char *get_dynamic_line(FILE *f) {
size_t bytes_read = 0;
char *bytes = NULL;
do {
if ((bytes_read & (bytes_read + 1)) == 0) {
void *temp = realloc(bytes, bytes_read * 2 + 1);
if (temp == NULL) {
free(bytes);
return NULL;
}
bytes = temp;
}
int c = fgetc(f);
bytes[bytes_read] = c >= 0 && c != '\n'
? c
: '\0';
} while (bytes[bytes_read++]);
return bytes;
}

traversing C string: get the last word of a string

how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
char str[80];
str = "my cat is yellow";
How would I get yellow?
Something like this:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
In case you don't want to use 'strrchr' function, Here is the solution.
i = 0;
char *last_word;
while (str[i] != '\0')
{
if (str[i] <= 32 && str[i + 1] > 32)
last_word = &str[i + 1];
i++;
}
i = 0;
while (last_word && last_word[i] > 32)
{
write(1, &last_word[i], 1);
i++;
}
I would use function strrchr()
The best way to do this is to take advantage of existing solutions. One such solution (to a much more general problem) is Perl Compatible Regular Expressions, an open-source regular expression library for C. So, you can match the string "my cat is yellow" with the regular expression \b(\w+)$ (expressed in C as "\b(\w+)$") and keep the first captured group, which is "yellow."
(heavy sigh) The original code is WRONG in standard / K&R / ANSI C! It does NOT initialize the string (the character array named str)! I'd be surprised if the example compiled. What your program segment really needs is
if strcpy(str, "my cat is yellow")
{
/* everything went well, or at least one or more characters were copied. */
}
or, if you promised not to try to manipulate the string, you could use a char pointer to the hard-coded "my cat is yellow" string in your source code.
If, as stated, a "word" is bounded by a space character or a NULL character, then it would be faster to declare a character pointer and walk backwards from the character just before the NULL. Obviously, you'd first have to be sure that there was a non-empty string....
#define NO_SPACE 20
#define ZERO_LENGTH -1
int iLen;
char *cPtr;
if (iLen=strlen(str) ) /* get the number of characters in the sting */
{ /* there is at least one character in the string */
cPtr = (char *)(str + iLen); /* point to the NULL ending the string */
cPtr--; /* back up one character */
while (cPtr != str)
{ /* make sure there IS a space in the string
and that we don't walk too far back! */
if (' ' == *cPtr)
{ /* found a space */
/* Notice that we put the constant on the left?
That's insurance; the compiler would complain if we'd typed = instead of ==
*/
break;
}
cPtr--; /* walk back toward the beginning of the string */
}
if (cPtr != str)
{ /* found a space */
/* display the word and exit with the success code */
printf("The word is '%s'.\n", cPtr + 1);
exit (0);
}
else
{ /* oops. no space found in the string */
/* complain and exit with an error code */
fprintf(STDERR, "No space found.\n");
exit (NO_SPACE);
}
}
else
{ /* zero-length string. complain and exit with an error code. */
fprintf(STDERR, "Empty string.\n");
exit (ZERO_LENGTH);
}
Now you could argue that any non-alphabetic character should mark a word boundary, such as "Dogs-chase-cats" or "my cat:yellow". In that case, it'd be easy to say
if (!isalpha(*cPtr) )
in the loop instead of looking for just a space....

Resources