Using strcmp in a while condition to break the loop [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to write a program where the program needs to loop and get input from the user. In order to break the loop, the user will need to type exit on the keyboard.
The following is my code:
int main()
{
char input[100];
char terminate[100]="$exit";
//if input does not equals to terminate keep asking user for input
while(strcmp(input, terminate)!=0)
{
printf("$");
fgets(input,100,stdin);
}//otherwise, exit the program
}
I tried testing the code above but it keeps on looping even after typing the word exit. Your assistance is greatly appreciated. :)

fgets will read the EOL character which will be included in the final string.
You may use strncmp to just use the characters from "terminate": strncmp(input, terminate, strlen(terminate).

There are two (and possibly three) problems in your code as you show it:
The first, which is very serious, is that you use input before it's initialized. That means the contents of the array is indeterminate (and could be seen as "random" or "garbage"). That will very likely lead to undefined behavior when you use it in strcmp because it's not a proper null-terminated string.
The second problem is that fgets adds the ending newline in the buffer, so unless you remove it or add a newline in the string you compare with the strings will never be equal.
You can easily remove the newline from the input string by using the strcspn function:
input[strcspn(input, "\n")] = 0;
The possible third problem is that you seem to be adding the prompt $ in the string you compare. Unless the user actually writes the $ in the input given, it will not be part of the input.
You also don't need to use as many characters for the terminate array. Instead let the compiler decide the proper amount:
char terminate[] = "exit"; // The size of the array will be 5, including null-terminator

Figured it out. Here is my solution:
while(strncmp(input, terminate,4)!=0)
{
printf("$");
fgets(input,100,stdin);
}
use strncmp instead of strcmp.

Related

Print a string without knowing max size [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am supposed to print out Number of letters in a word given by the user and also print it out in reverse. I struggle to find out how i am supposed to declare the array when i dont have the size of the string. I thought of using gets and then a for loop but can’t figure out how to define char in both the function for printing number of letters and printed in reverse.
When you obtain the string - say, with scanf() or fgets() - you can specify a maximum "field width", i.e. the maximum number of characters to read into your buffer. So, you first set the buffer size, then you read into it.
Now, after you've read the string, you can determine it's length the usual C way with strlen() on your buffer. Alternatively, if you're using scanf(), you can use the "%n" specifier to store the number of characters consumed, so that scanf("%49s%n", buffer, &count); will scan the string into the 50-chararacter-long buffer and the number of characters into count.
PS - Don't use the gets() function though... Why is the gets function so dangerous that it should not be used?
Counting characters in a word entered by the user is easy. Set a counter to zero. Read one character at a time (e.g., using getchar). If the character is a letter, increment the counter and continue the loop. If it is not a letter or the attempt to read fails (e.g., getchar returns EOF), exit the loop and print the value of the counter. For embellishment, you might add code to ignore white space before the letters start, to ignore white space after the letters end (until a new-line character is seen), and/or to report a warning if any other characters are seen. –
Eric Postpischil

How to strtok() string using the null character as the delimiter? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried inputting the null character into the list of delimiters but it would not accept it. I tried inputting "\0" but it wouldn't accept it. I even tried putting in the double quotes with escape characters but it still would not accept it.
Is there a way I could do this?
According to strtok(3) this function is used to isolate sequential tokens in a null-terminated string. So the answer is no, not using strtok, since that function cannot compare a \0 separator from the terminator. You will have to write your own function (which is trivial).
Also read the BUGS section in the strtok man page ... better avoid using it.
If you are allowed to end your string with a double \0 as sentinel you can build your own function, something like:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *s = "abc\0def\0ghi\0";
char *p = s;
while (*p) {
puts(p);
p = strchr(p, '\0');
p++;
}
return 0;
}
Output:
abc
def
ghi
For better or worse, C decided that all strings are null terminated, so you can't parse based on that character.
One workaround would be to replace all nulls in your (non-string) binary buffer with something you know doesn't occur in the buffer, then use that as your separator treating the buffer as char*.
In C, strings are just char arrays that must end with a null character. If a string in memory is not terminated that way, the program will endlessly read memory until a null char is found and there is no way to determine where it will be since memory changes constantly. Your best bet is to create an array of char pointers (strings) and populate them using better organization.

how to check if a variable is equal to a word [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code. I want that when the user writes yes the program will print OK.
However, the program writes
"yes is undeclared".
How can I make the program treat to 'yes' as a word and not as a variable?
char a = ' ';
scanf("%c",&a);
if(a == yes)
{
printf("OK");
}
First thing first, 'yes' is not a word (sting, if you mean that), "yes" is.
That said, you're way out of league for the idea. One possible implementation can look like
First, you need to define an array for the input, like char a[12] = "no"; because you need to store more than one character as per your need. (the size used here is just indicative).
Scan the user input using scanf(), like scanf("%11s", a);
Use strcmp() from string.h, for comparison, like if (!strcmp(a, "yes")).
Another possible implementation could make use of an enum of "YES" and "no", take the user choice as integer and make use of the good old == comparison operator.
There are numerous problems in your code.
First of all, you declare a as a char (character) which means you can't compare it to "yes" because that's a string, or char array because this is C.
It's composed of 4 characters (3 for the text, 1 for the \0; in C "strings" are null-terminated so there has to be an ending character).
Declare your variable and read it like this:
#include <string.h> //you need this for string comparison
char a[10]; //arbitrary size, just make sure it's big enough for the input
scanf("%s", a);
//OR
fgets(a, sizeof(a), stdin); //use fgets if you need to read more than one word, scanf stops reading at whitespace
//don't use == to compare strings
if (!strcmp(a, "yes")){ //use quotes to delimit "words"
printf("OK\n");
}

Inputting an arithmatic statement in c and return the value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
(I am very bad at inputting/processing strings in C. Hope this question will teach me a lot.)
I am trying to make a function that will input an arithmatic string from stdin, e.g 23 + 45 * 6 - 5, and return the value.
There are multiple strings, entered one after another, and can be of any length and the operator precedence doesn't matter, i.e., it processes string sequentially.
The problems that I faced are :-
\n from previous string is also considered a string.So if I input 3 strings , it will actually be 6, 3 strings and 3 \n.
I used a char pointer and used char * input; scanf(" %s",input);, but in addition to above problem, I also get segmentation fault, which I guess is due to missing \0.
My question is forget what mess I did, what would you have done or what's the best way to handle string input in the above scenario. A dummy code is sufficient.Thanks.
What I was doing
#include <stdio.h>
int main()
{
int t; //no of test cases
char input;
scanf("%d",&t);
while(t--)
{
while((input=getchar())!='\n')
{
//use switch to identify char and follow appropriate action
printf("%c\n",input );
}
}
return 0;
}
As suggested by Joachim Pileborg, use fgets. Use a char array, instead of one char variable, to store the string.
char input[100];
fgets(input, sizeof(input), stdin);
The advantage of fgets over sscanf is that fgets can read spaces in your input.
It will include the end-of-line byte \n, so 3 strings will not turn into 6 strings.
As usual with fgets, there is an arbitrary limit on the length of the input. If the user inputs something longer than 98 bytes, the system cannot fit it all (plus end-of-line \n and end-of-string \0 bytes), and the program will receive truncated string.
If you cannot tolerate that, use getline (it's harder to use, so use fgets if in doubt).
After you scan your string in, check to see if it is a '\n', if it is just ignore processing it and move to the next one.
Or you could try:
char input[101];
scanf("%s\n", &input);
First of all. Your idea of writing an fomular expression analyzer as a first projekt is not a very good one. Start with a simpler project.
You get the sagmentation fault, because you try to read data (with the scanf()) into a not initialized pointer.
char *input;
will not allocate any memory for the string you want to read with scanf(). You have to use a buffer something like
char input[256];
and give the pointer to the buffer to scanf("%s",input) (oder for better understanding scanf("%s",&input[0]);
Anywhere, this buffer has only 255 chars to store and you must be aware, that if you enter more then 255 chars in the scanf() you will get an illegal memory access as well.
Claus

Dynamic memory allocation for input? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am having a lot of trouble starting my project. Here are the directions:
"Complete counts.c as follows:
Read characters from standard input until EOF (the end-of-file mark) is read. Do not prompt the user to enter text - just read data as soon as the program starts.
Keep a running count of each different character encountered in the input, and keep count of the total number of characters input (excluding EOF)."
The format my professor gave me to start is: `
#include <stdio.h>
int main(int argc, char *argv[]) {
return 0;
}
In addition to how to start the problem, I'm also confused as to why the two parameter's are given in the main function when nothing is going to be passed to it. Help would be much appretiated! Thank you!
`
Slightly tricky to see what you're having trouble with here. The title doesn't form a complete question, nor is there one in the body; and they seem to be hinting at entirely different questions.
The assignment tells you to read characters - not store them. You could have a loop that only reads them one at a time if you wish (for instance, using getchar). You're also asked to report counts of each character, which would make sense to store in an array. Given that this is of "each different character", the simplest way would be to size the array for all possible characters (limits.h defines UCHAR_MAX, which would help with this). Remember to initialize the array if it's automatically allocated (the default for function local variables).
Regarding the arguments to main, this program does not need them, and the C standard does allow you to leave them out. They're likely included as this is a template of a basic C program, to make it usable if command line arguments will be used also.
For more reference code you might want to compare the word count utility (wc); the character counting you want is the basis of a frequency analysis or histogram.
This should give you a start to investigate what you need to learn to complete your task,
Initially declare a character input buffer of sufficient size to read chars as,
char input[SIZE];
Use fgets() to read the characters from stdin as,
if (fgets(input, sizeof input, stdin) == NULL) {
; // handle EOF
}
Now input array has your string of characters which you to find occurrence of characters. I did not understand When you say different characters to count, however you have an array to traverse it completely to count the characters you need.
Firstly, luckily for you we will not need dynamic memory allocation at all here as we are not asked to store the input strings, instead we simply need to record how many of each ascii code is input during program run, as there a constant and finite number of those we can simply store them in a fixed size array.
The functions we are looking at here (assuming we are using standard libs) are as follows:
getchar, to read chars from standard input
printf, to print the outputs back to stdout
The constructs we will need are:
do {} while, to loop around until a condition is false
The rest just needs simple mathematical operators, here is a short example which basically shows a sample solution:
#include <stdio.h>
int main(int argc, char *argv[])
{
/* Create an array with entries for each char,
* then init it to zeros */
int AsciiCounts[256] = {0};
int ReadChar;
int TotalChars = 0;
int Iterator = 0;
do
{
/* Read a char from stdin */
ReadChar = getchar();
/* Increment the entry for its code in the array */
AsciiCounts[ReadChar]++;
TotalChars++;
} while (ReadChar != EOF);
/* Stop if we read an EOF */
do
{
/* Print each char code and how many times it occurred */
printf("Char code %#x occurred %d times\n", Iterator, AsciiCounts[Iterator]);
Iterator++;
} while (Iterator <= 255);
/* Print the total length read in */
printf("Total chars read (excluding EOF): %d", --TotalChars);
return 0;
}
Which should achieve the basic goal, however a couple of extension exercises which would likely benefit your understanding of C. First you could try to convert the second do while loop to a for loop, which is more appropriate for the situation but I did not use for simplicity's sake. Second you could add a condition so the output phase skips codes which never occurred. Finally it could be interesting to check which chars are printable and print their value instead of their hex code.
On the second part of the question, the reason those arguments are passed to main even though they are ignored is due to the standard calling convention of c programs under most OSes, they pass the number of command line arguments and values of each command line argument respectively in case the program wishes to check them. However if you really will not use them you can in most compilers just use main() instead however this makes things more difficult later if you choose to add command line options and has no performance benefit.

Resources