My Strlen Syntax Not Written Well? [closed] - c

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 5 years ago.
Improve this question
if I write more than 20 charcters in my program it runs through it and skips my if statement if(length > 20). What did I do wrong?
printf("\nEnter Your Product:");
fgets(item_name, 20, stdin);
length = strlen(item_name);
if(length > 20){
Errorlevel("Input Greater Than 20");
}

You set fgets to gather a maximum of 20 chars. Thus, if(length > 20) is always false.
See documentation about fgets

The fgets will read up the the requested number of character minus one. The size you pass to the fgets function includes the terminator.
So no matter how many characters you write, the length will never be longer than 19 characters.
A simple way to check if to many characters were input is to see if the last character (not the string terminator) is a newline or not. If it's not then 19 or more characters were entered as input.

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

Using strcmp in a while condition to break the loop [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 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.

'Character Array' of integers to 'Integer array' [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
My Requirement :
Taking some (unknown number) of integers as input from user and store them in a numeric array.
Eg: input: 25 3 4 78. I want them to be stored in a numeric array, say num as
num[0] = 25
num[1] = 3
num[2] = 4
num[3] = 78
. . .
What I did :
Stored the input in a character array.
gets(arr);
//takes input from command prompt and stores in a string
Then I'm trying to find spaces and separate the characters, but it turns out that a double digit number(say,25) is stored as 2 and 5 but not as 25.
How do I achieve this?
Well, as you did not show your code, I'll also not provide any code, but I'll be more than happy to provide you with the flow-chart.
Define one array large enough (maybe change to dynamic allocation later).
Take the input from user (not command line arguments) using fgets().
use strtok() to tokenize the input using space as delimiter.
If a non-NULL token is received, use strtol() to convert the token to int or long.
If strtok() returned NULL means you've got all the tokens and the input is empty, finish up, you got your int array.

Forcing users to write input in a specific format [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
i'm making a program in C. that keeps track of items in a warehouse.
and i want to force the user to include at least one number!
example dvd1, dvd2. hello1, hello20
is there a way to do this?
at this moment i am using scanf.
and i want the product code to have the requirement format of xx-xxx-xxx were x are numbers.
i'm using scanf ( %[0-9-]s
Mvh Anton!
scanf doesn't work like that, it doesn't have in-depth validation.
You need to read the input into a char array, then loop through each character and see if it is a digit.
Something like this (untested):
char buffer[1000];
int i = 0, hasDigit = 0;
scanf("%s", buffer);
while (i < sizeof(buffer) && buffer[i] != 0 && !hasDigit)
{
hasDigit = isdigit(buffer[i]);
i++;
}
// if hasDigit is 0, there are no digits
Note: scanf isn't great, since if you enter more characters than fit in the buffer it can cause a buffer overflow. It is better to use fgets(buffer, sizeof(buffer), stdin);
Read the input and you can iterate through as in This SO question. You can check to see if chars match the input you want pretty easily from that point on.

atoi() returning 0 from char array [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 am writing a program in which stdin is read into a buffer, then processed. The vast majority of these items that need to be processed are strings (or well, character arrays). However, I do have one item that needs to be read in as a character array and then converted to int for ease of use in the future.
for(i=0; i<n; i++){
num[i] = buff[(i)];
printf("%c", num[i]);
}
convert = atoi(num);
So I know for sure that the correct group of characters is being read into num because the printf for that is correct. However, when I try to print convert I end up getting 0, and I'm very perplexed as to what I'm doing wrong. I know that the 0 return means that a valid conversion could not be performed, but I don't know what's making it invalid. Any tips?
EDIT: Sorry for not including these before >_<
n is the number of chars in the buff array
buff is the buffer array stdin is read into
atoi is a function that gives you no means to analyze error conditions. On top of that, it produces undefined behavior in overflow situations. Don't ever use atoi (or atof or anything from ato... group) in real-life programs. It is practically useless.
To perform string-to-number conversions use strtol (and other functions from strto... group).
Now, what is inside your num at the moment you call your atoi? Is your num properly zero-terminated?

Resources