switching from getchar to fgets - c

I am trying to switching my use of getchar to fgets but, when using getchar, the entire code does not work.
//fgets(line, sizeof(line), stdin);
while(fgets(line, sizeof(line), stdin))
{
portNum[sizeof(line)] = (char)line;
}
while((c = getchar()) != '\n')
{
portNum[num++] = c;
}
portNum[num] = '\0';
How can I make equal for those two functions to work properly?

You usage of fgets is wrong.
fgets Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
In your case fgets will read all the characters until newline is encountered.
Also, the parameters usage is wrong.
char * fgets ( char * str, int num, FILE * stream );
str => Pointer to an array of chars where the string read is copied.
num => Maximum number of characters to be copied into str (including the
terminating null-character).
stream => Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.
Refer to the fgets documentation for more information.
fgets man page

OP's fgets() usage is unclear and portNum[sizeof(line)] = (char)line; is certainly in error.
Instead: how to make the below getchar() code more fgets()-like:
// assumed missing code
#define N 100
int c;
char portNum[N];
size_t num = 0;
// size and EOF detection added (which should have been there)
while(num + 1 < sizeof portnum && (c = getchar()) != '\n' && c != EOF) {
portNum[num++] = c;
}
portNum[num] = '\0';
// assumed missing code
if (c == EOF && num == 0) Handle_EndOfFile_or_InputError();
else ...
This can be replaced with fgets() code
#define N 100
char portNum[N+1]; // 1 larger for the \n
if (fgets(portNum, sizeof portNum, stdin)) {
// lop off potential trailing \n
portNum[strcspn(portNum, "\n")] = '\0';
...
} else {
Handle_EndOfFile_or_InputError();
}

Related

How to accept string input only if it of certain length in C else ask user to input the string again

How to accept set of strings as input in C and prompt the user again to re-enter the string if it exceeds certain length. I tried as below
#include<stdio.h>
int main()
{
char arr[10][25]; //maximum 10 strings can be taken as input of max length 25
for(int i=0;i<10;i=i+1)
{
printf("Enter string %d:",i+1);
fgets(arr[i],25,stdin);
}
}
But here fgets accepts the strings greater than that length too.
If the user hits return, the second string must be taken as input. I'm new to C
How to accept string input only if it of certain length
Form a helper function to handle the various edge cases.
Use fgets(), then drop the potential '\n' (which fgets() retains) and detect long inputs.
Some untested code to give OP an idea:
#include <assert.h>
#include <stdio.h>
// Pass in the max string _size_.
// Return NULL on end-of-file without input.
// Return NULL on input error.
// Otherwise return the buffer pointer.
char* getsizedline(size_t sz, char *buf, const char *reprompt) {
assert(sz > 0 && sz <= INT_MAX && buf != NULL); // #1
while (fgets(buf, (int) sz, stdin)) {
size_t len = strlen(buf);
// Lop off potential \n
if (len > 0 && buf[--len] == '\n') { // #2
buf[len] = '\0';
return buf;
}
// OK if next ends the line
int ch = fgetc(stdin);
if (ch == '\n' || feof(stdin)) { // #3
return buf;
}
// Consume rest of line;
while (ch != '\n' && ch != EOF) { // #4
ch = fgetc(stdin);
}
if (ch == EOF) { // #5
return NULL;
}
if (reprompt) {
fputs(reprompt, stdout);
}
}
return NULL;
}
Uncommon: reading null characters remains a TBD issue.
Details for OP who is a learner.
Some tests for sane input parameters. A size of zero does not allow for any input saved as a null character terminated string. Buffers could be larger than INT_MAX, but fgets() cannot directly handle that. Code could be amended to handle 0 and huge buffers, yet leave that for another day.
fgets() does not always read a '\n'. The buffer might get full first or the last line before end-of-file might lack a '\n'. Uncommonly a null character might be read - even the first character hence the len > 0 test, rendering strlen() insufficient to determine length of characters read. Code would need significant changes to accommodate determining the size if null character input needs detailed support.
If the prior fgets() filled its buffer and the next read character attempt resulted in an end-of-file or '\n', this test is true and is OK, so return success.
If the prior fgetc() resulted in an input error, this loops exits immediately. Otherwise, we need to consume the rest of the line looking for a '\n' or EOF (which might be due to an end-of-file or input error.)
If EOF returned (due to an end-of-file or input error), no reason to continue. Return NULL.
Usage
// fgets(arr[i],25,stdin);
if (getsizedline(arr[i], sizeof(arr[i]), "Too long, try again.\n") == NULL) {
break;
}
This code uses a buffer slightly larger than the required max length. If a text line and the newline can't be read into the buffer, it reads the rest of the line and discards it. If it can, it again discards if too long (or too short).
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define INPUTS 10
#define STRMAX 25
int main(void) {
char arr[INPUTS][STRMAX+1];
char buf[STRMAX+4];
for(int i = 0; i < INPUTS; i++) {
bool success = false;
while(!success) {
printf("Enter string %d: ", i + 1);
if(fgets(buf, sizeof buf, stdin) == NULL) {
exit(1); // or sth better
}
size_t index = strcspn(buf, "\n");
if(buf[index] == '\0') { // no newline found
// keep reading until end of line
while(fgets(buf, sizeof buf, stdin) != NULL) {
if(strchr(buf, '\n') != NULL) {
break;
}
}
if(feof(stdin)) {
exit(1); // or sth better
}
continue;
}
if(index < 1 || index > STRMAX) {
continue; // string is empty or too long
}
buf[index] = '\0'; // truncate newline
strcpy(arr[i], buf); // keep this OK string
success = true;
}
}
printf("Results:\n");
for(int i = 0; i < INPUTS; i++) {
printf("%s\n", arr[i]);
}
return 0;
}
The nice thing about fgets() is that it will place the line-terminating newline character ('\n') in the input buffer. All you have to do is look for it. If it is there, you got an entire line of input. If not, there is more to read.
The strategy then, is:
fgets( s, size_of_s, stdin );
char * p = strpbrk( s, "\r\n" );
if (p)
{
// end of line was found.
*p = '\0';
return s; (the complete line of input)
}
If p is NULL, then there is more work to do. Since you wish to simply ignore lines that are too long, that is the same as throwing away input. Do so with a simple loop:
int c;
do c = getchar(); while ((c != EOF) && (c != '\n'));
Streams are typically buffered behind the scenes, either by the C Library or by the OS (or both), but even if they aren’t this is not that much of an overhead. (Use a profiler before playing “I’m an optimizing compiler”. Don’t assume bad things about the C Library.)
Once you have tossed everything you didn’t want (to EOL), make sure your input isn’t at EOF and loop to ask the user to try again.
Putting it all together
char * prompt( const char * message, char * s, size_t n )
{
while (!feof( stdin ))
{
// Ask for input
printf( "%s", message );
fflush( stdout ); // This line _may_ be necessary.
// Attempt to get an entire line of input
if (!fgets( s, n, stdin )) break;
char * p = strpbrk( s, "\r\n" );
// Success: return that line (sans newline character(s)) to the user
if (p)
{
*p = '\0';
return s;
}
// Failure: discard the remainder of the line before trying again
int c;
do c = getchar(); while ((c != EOF) && (c != '\n'));
}
// If we get this far it is because we have
// reached EOF or some other input error occurred.
return NULL;
}
Now you can use this utility function easily enough:
char user_name[20]; // artificially small
if (!prompt( "What is your name (maximum 19 characters)? ", user_name, sizeof(user_name) ))
{
complain_and_quit();
// ...because input is dead in a way you likely cannot fix.
// Feel free to check ferror(stdin) and feof(stdin) for more info.
}
This little prompt function is just an example of the kinds of helper utility functions you can write. You can do things like have an additional prompt for when the user does not obey you:
What is your name? John Jacob Jingleheimer Schmidt
Alas, I am limited to 19 characters. Please try again:
What is your name? John Schmidt
Hello John Schmidt.

How to read arbitrary length input from stdin properly?

I want to ask user to input some string in each loop. However, the code below will skip loop multiple times if the length of input is greater than 2?
Why is this happening and what's the best way to read arbitrary length input from stdin?
#include <stdio.h>
int main(void)
{
char in[2];
while (in[0] != 'q') {
puts("Enter: ");
fgets(in, 3, stdin);
}
return 0;
}
First, your buffer is not large enough to hold a 2 character string. Strings in C need to have an extra '\0' appended to them to mark the end. Second, fgets will leave chars in the input buffer when the input string is longer than the buffer passed to it. You need to consume those characters before calling fgets again.
Here is a function, similar to fgets in that it will only read buffer_len - 1 chars. And it will also consume all chars until the newline or EOF.
int my_gets(char *buffer, size_t buffer_len)
{
// Clear buffer to ensure the string will be null terminated
memset(buffer, 0, buffer_len);
int c;
int bytes_read = 0;
// Read one char at a time until EOF or newline
while (EOF != (c = fgetc(stdin)) && '\n' != c) {
// Only add to buffer if within size limit
if (bytes_read < buffer_len - 1) {
buffer[bytes_read++] = (char)c;
}
}
return bytes_read;
}
int main(void)
{
char in[3]; // Large enough for a 2 char string
// Re-arranged to do/while
do {
puts("Enter: ");
my_gets(in, sizeof(in)); // sizeof(in) == 3
} while (in[0] != 'q');
return 0;
}

Buffer and its interaction with function?

I am facing some problems while understanding the following code.
It is a program to read Strings from keyboard if the length of the String is lesser than the specified size (i.e 'n' here).
If the length of a string is larger than the specified size, the remaining characters on the line will be discarded.
More specifically, I want to know what is happening inside the buffer and how getchar() is reading the data and not storing it in the buffer.
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) // i.e., ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else // must have words[i] == '\0'
while (getchar() != '\n')
continue;
}
return ret_val;
}
The code is slightly flawed, but does more or less the job outlined. It uses fgets() to do a lot of the work. That reads up to n - 1 characters from standard input. When it returns, there are a few possibilities:
(EOF) Nothing was available to be read. Nothing has been put in the buffer, but fgets() returned NULL.
(Normal) A line has been read and fitted into the buffer st. The buffer includes the newline.
(Overlong) Part of a line has been read, but the input did not find a newline.
(EOF without newline) Some data was read, but there wasn't a newline before EOF was detected.
Case 1 is simplest: the code returns NULL. Case 2 is handled by scanning the string that's read to find the newline. If the newline is found, it is overwritten with a null byte. Case 3 is handled at the same time; if the value found isn't a newline, it must be the null byte. The code drops into a loop that reads more characters until a newline is read. Case 4 is similar to case 3 in effect, but the code in the loop mishandles this — it doesn't detect and handle EOF, so the code would fall into an indefinite loop. That's a bug that needs to be fixed.
The getchar() loop doesn't assign anything to the buffer st — it makes no changes to st. That continues to contain a null terminated string as read by fgets(). The getchar() loop reads and discards any characters left on the line that was read that did not fit into the buffer.
The code should be:
char *s_gets(char *st, int n)
{
assert(n > 1 && st != NULL);
char *ret_val = fgets(st, n, stdin);
if (ret_val != NULL)
{
int i = 0;
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
{
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
}
}
return ret_val;
}
The return value of NULL or the original string is the same as fgets() uses, but it isn't the most useful return value. It would be more useful, most often, if the code returned the length of the string that it read, or returned EOF if it encountered EOF (or a read error). The information is readily available — in the variable i.

C - Prompted for a second input and does nothing

this is my code below. What it does is not the issue. The issue is that once it is run, I put in my input and if its too small it will ask for input again on the second line which appears to have no affect the flow of my program. If I fill the buffer (which I'm assuming 100 or more) then I am not asked for a second prompt.
#include <stdio.h>
#include <string.h>
int main()
{
int ch;
char x[3];
char *word, string1[100];
x[0]='y';
while(x[0]=='y'||x[0]=='Y')
{
fgets(string1, 100, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
printf("The string is: %s", string1);
word = strtok(string1, " ");
while(word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
printf("Run Again?(y/n):");
fgets(x, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
return 0;
}
EDIT:
I have replaced,
fgets(string1, 100, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
With,
fgets(string1, 100, stdin);
if (string1[98] != '\n' && string1[99] == '\0')
{
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
From the man page:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops
after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the
last character in the buffer.
fgets will place all input, up to 99 chars, into string1. If you input 98 characters and hit enter (creating a 99th \n), then all 100 will be used as the last one is a \0 terminator.
Then you fall into that small while loop which does nothing but consume another line of input. If you input less than the max for your string, then input is halted while that loop waits for a \n.
If you input >98 characters, then the first 99 are saved to your input string, and the remainder along with that final \n are immediately run through that while loop, causing it to exit quickly enough that it may seem to be skipped.
I hope that helps. Unfortunately I can't comment and ask for clarification, so I'll say here that it's a little difficult to tell what exactly you want fixed or made clear.
The answer to your question is right here: man fgets
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
To know if fgets used the whole buffer, write some non-NUL byte into the end of the buffer. If, after calling fgets, that byte has been overwritten with a NUL, it means the buffer is full. If the character directly before it is not a newline, then there's more input still to be read.
buffer[size - 1] = 'a'; // any character that's not '\0'
fgets(buffer, size, stdin);
if (buffer[size - 1] == '\0' && buffer[size - 2] == '\n') {
// handle extra input
}
Alternatively, you could just read bytes one at a time using getchar.
I think you need this:
Note: x must be int if you want to compare it against EOF
int main()
{
int x;
char *word, string1[100];
do
{
fgets(string1, 100, stdin);
printf("The string is: %s", string1);
word = strtok(string1, " ");
while(word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
printf("Run Again?(y/n):");
x = fgetc(stdin);
fgetc(stdin); // absorb `\n`
}
while( (x=='y'||x=='Y') && x != EOF) ;
return 0;
}

How can know if the end of line in C

If I do :
int main(){
const int LENGTH_LINE = 100;
char line[LENGTH_LINE];
int len;
FILE* fp = fopen(file.txt,"r");
fgets(line,LENGTH_LINE,fp);
len = strlen(line);
if(line[len-1] == '\n')
printf("I've a line");
//This work if the line have \n , but if the end line of the text dont have \n how can do it?
}
I need to know if I take a whole line with fgets because I got a delimiter.
According to http://en.cppreference.com/w/c/io/fgets
Reads at most count - 1 characters from the given file stream and stores them in str.
Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
So, once fgets returns, there are 3 possibilities
LENGTH_LINE was reached
We got a newline
EOF was reached.
I'm assuming you have a line in cases 2 and 3.
In this case the detection condition is :
line[len-1] == '\n' || feof(fp)
Check for the newline character:
size_t len = 0;
// ... your code using fgets
len = strlen(line);
if ((len > 0) && (line[len - 1] == '\n'))
// your input contains the newline
After the fgets call, your line may not have a newline at the end if:
The character limit was reached before a newline was scanned - in your case this is LENGTH_LINE.
The end-of-file (EOF) was reached before a newline.
There was a read error, but in case of an error consider the contents of line unusable.
You should be looking at the return value from fgets so that you'll be able to handle the EOF: fgets returns NULL upon end-of-file or a read error. You can use feof to check for the end-of-file.
If you check feof, and know that you're at the end of your input with no fgets errors, then even without a newline character on the final line you'll know that you've read the entire line.
If for some reason you must have a newline character terminating each line, you can add it yourself:
// you've checked for EOF and know this is your final line:
len = strlen(line);
if (line[len-1] == '\n')
printf("I've a line");
else if ((len + 1) < LENGTH_LINE)
{
line[len] = '\n';
line[len + 1] = '\0';
}
else
// no room in your line buffer for an add'l character
Use like this
while(fgets(line,LENGTH_LINE,fp)!=EOF)
// your code here
Why not just use fgetc instead? That way you can just keep scanning until you get to the end of the line so you don't have to check if you have it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[100];
int ch, i = 0;
FILE* fp = fopen(file.txt,"r");
while(ch != '\n' || ch != '\r' || ch != EOF) //or ch != delimiter
{
ch = fgetc(fp);
line[i] = ch;
i++;
}
line[i] = '\n';
line[i+1] = 0x00;
return 0;
}
In that example I just look for a new line, return, or EOF character but you can really make it look for anything you like (e.g. your delimiter). So if your delimiter was q you would just do
while(ch != 'q')...

Resources