Print a string without knowing max size [closed] - arrays

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

Related

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.

fgets() and text files [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 3 years ago.
Improve this question
My book mentions that fgets will read until it meets the (n-1)th character or a character of a new line. By character of new line do we only mean Enter (\n)? I am asking this because what I did was to create a text file on which I started typing in some nonsense, surpassing the character limit of each line meaning that I used more than one lines. After that I used fgets and what I expected was it to read only the characters in the first line of the text file but what it did was read all of them.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char box[5000];
FILE *fp;
fp = fopen("test.txt", "r");
fgets(box, 5000, fp);
puts(box);
}
Test.txt (The text is random that's why it's silly) (285 characters):
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk25kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkggggggggggiiiiiiiiiiiiiiiiiiii
So the result I expected was for it to print only part of the text and actually as many characters as the limit that is set for one line, minus one, (which I think is something above 250). But instead of that, it prints all of them. Note: The same thing happens even I type even more characters in the file.
You seem to be assuming that there's an upper limit, perhaps 255 characters, on the length of a line in a text file. C imposes no such limit, except indirectly by using int as the size argument to fgets.
Your program defines a 5000-character array and calls fgets with a length argument of 5000. That means it can read a single line of up to 5000 characters (or close to that; I'm ignoring a couple of off-by-one issues for the '\n' and '\0' characters). The input line in your question is only 285 characters long, so your program will easily read it as a single line.
You can try changing the length of your array to see what happens when an input line is too long to fit:
char box[255];
...
fgets(box, sizeof box, fp);
Note that using sizeof box rather than repeating the number means the call won't get out of sync with the array size.
It only stops at the newline character \n or at n-1 characters. There is no newline character other than \n.
As you set the limit for your buffer and the amount fgets can read to 5000, it can easily read all the characters in your file and print them.
There is no line length limit in ISO C (ISO/IEC 9899), whether one is imposed by your book or not. Your book is probably outdated.

Difference between gets() and scanf("%s") [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 3 years ago.
Improve this question
I declared a character pointer, and used it for to scan a string in runtime; I don't know the number of characters that I'm going to enter, so I didn't use calloc or malloc. The program ends when it reached the line scanf("%s", NewMsg_au8).
I'm using CodeBlocks 17.12 editor.
I tried hard coding one of the input case like, NewMsg_au8="0123456789ABCDEF"; — that works fine.
uint8 * NewMsg_au8;
scanf("%s",NewMsg_au8);//<==
printf("Your entered message is: %s\n",NewMsg_au8);
return NewMsg_au8;
gets(s) and scanf("%s", s) are both unsafe and potentially incorrect because:
with those calls as shown, there is no way for either function to determine the maximum number of characters to store into the array pointed to by s, hence overlong input will cause a buffer overrun leading to undefined behavior.
in your case, it is even worse as s is an uninitialized pointer, so both functions would try a store data into a random address in memory causing undefined behavior in all cases.
gets() cannot be used safely and has been deprecated in and then removed from the C Standard.
However, scanf() can be given a limit with a numeric value between % and s:
#include <stdio.h>
#include <string.h>
char *read_string(void) {
char buf[100];
if (scanf("%99s", buf) == 1) {
printf("Your entered message is: %s\n", buf);
return strdup(buf); /* return an allocated copy of the input string */
} else {
/* no input, probably at end of file */
return NULL;
}
}
Note how only 99 characters can be stored into the array buf to allow for the null byte terminator that marks the end of a C string. The %99s conversion specification lets scanf() store at most 100 bytes into buf, including the '\0' terminator.
That is a typical beginners error. You do not save data in pointers (with gets() or scanf()) but in buffers.
Therefore, you have 2 solutions:
Use an array big enough to hold the data. You have to decide yourself what "big enough" means, according to the details of your application.
Use a pointer, and then allocate memory with malloc() - the size, again, you have to decide it. Do not forget to deallocate the memory when you no longer need it.
I tried hard coding one of the input case like, NewMsg_au8="0123456789ABCDEF"; — that works fine.
That is normal, because in that case the compiler automatically allocates enough memory to hold the string.
Please always remember when working with strings: you always need to allocate an extra byte for the terminating null character - the mark of the end of the string. Otherwise, you will need to ask questions again :)

fgets to include text after newline [duplicate]

This question already has answers here:
Correct way to read a text file into a buffer in C? [duplicate]
(8 answers)
Closed 7 years ago.
I want to make an array of characters and store the whole input in it(even if the input contains "\n" at some point. When i use:
char vhod[50];
fgets(vhod, sizeof(vhod), stdin);
it stores the input UNTIL the first newline. How to get the whole text in this array(including the text after the new line).
Example:
if my text is:
Hello I need new keyboard.
This is not good.
my array will only contain "Hello I need new keyboard.". I want to be able to read everything till the end of input a < input-1
I cannot use FILE open/close/read functions since it is input from keyboard.
While fgets() is designed to read up to a '\n' character or the specified number of bytes, you can use fread()1 instead, like this
size_t count = fread(vhod, 1, sizeof(vhod), stdin);
and count will contain the number of items read, which in this case is the same as the number of bytes since you are providing size 1 i.e. sizeof(char).
Note however that you must be very careful to add a terminating '\0' if you are going to use any function that assumes a terminating '\0'.
1Read the manual for more information.

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

Resources