Input string with getchar - c

I am trying to read a string into a char array with a length chosen by the user. The problem is that getchar() doesn't stop reading until the user manually enters a newline by pressing enter, based on my code. I have read through other's threads, and I understand why I'm not able to do it this way, it's just completely contradictory to my assignment handout.
int chPrompt(int nchars);
void strInput(char str[], int nchars);
int main(void) {
int nchars = chPrompt(nchars);
char str[nchars];
strInput(str, nchars);
return 0;
}
int chPrompt(int nchars) {
printf("How many chars do you need to input? >");
return scanf("%i", &nchars);
}
void strInput(char str[], int nchars) {
int i = 0;
while((str[i] = getchar()) != '\n') {
if(i > nchars-1)
break;
i++;
}
str[i] = '\0';
//Troubleshooting
printf("%s %d", str, strlen(str));
}
This is what the handout says:
Input a string from the keyboard (spaces included) using the technique we talked
about (while with getchar(), not gets() , fgets()or scanf() ),
augmented so that it will input any amount up to, but no more than, 80
characters. Be sure that there’s a null in the proper location after the input.
The technique we talked about in class was the while loop with getchar assignment to char array.
My question:
My professor is very adamant about his instructions. In this handout, he is specifically telling me to input any amount up to, but no more than, 80. This is contradicting the functionality of getchar, correct? Is there any way to limit the length of a string, using this 'technique'?
On some of the threads I found, people mentioned it might be OS dependent. So, if that matters, I am on Windows 8.1.

Op's code is close.
"getchar() doesn't stop reading until the user manually enters a newline by pressing enter" is incorrect.
Typical user input is line buffered. Nothing is given to the program until Enter occurs. At that time the entire line is given to the program. getchar() consumes 1 char at a time from stdin.
1) Need to allocate sufficient buffer memory #Grzegorz Szpetkowski
2) Read input as an int and read extra as needed.
3) Do not return the value from scanf() as the number of to read.
4) Read remaining line after reading the number of char to be read. #Grzegorz Szpetkowski
getchar() returns an unsigned char or EOF. That is typically 257 different results. Reading getchar() into a char loses that distinction.
void strInput(char str[], int nchars) {
int i = 0;
int ch;
while((ch = getchar()) != '\n' && ch != EOF ) {
if (i < nchars) {
str[i++] = ch;
}
}
str[i] = '\0';
}
int main(void) {
int nchars = chPrompt(nchars);
char str[nchars + 1]; // + 1
strInput(str, nchars);
//Troubleshooting
printf("'%s' %zu", str, strlen(str));
return 0;
}
int chPrompt(int nchars) {
printf("How many chars do you need to input? >");
if (scanf("%i", &nchars) != 1) {
printf("Unable to read #\n");
exit(-1);
}
// Consume remaining text in the line
int ch;
while((ch = getchar()) != '\n' && ch != EOF );
return nchars;
}
Note: strlen() returns type size_t, not int, this may/may not be the same on your platform, best to use the right format specifier "%zu" with strlen(). Alternatively use:
printf("'%s' %d", str, (int) strlen(str));

This code could be corrected in few more places (e.g. counting the characters inputted so that you allow the user to input no more than 80 characters, etc.) but this will point you in the right direction:
#include <stdio.h>
#include <string.h>
void strInput(char str[], int nchars);
int main(void) {
int nchars = 0;
printf("How many chars do you need to input?\n");
scanf("%d\n", &nchars);
char str[nchars+1];
strInput(str, nchars);
return 0;
}
void chPrompt(int nchars) {
}
void strInput(char str[], int nchars) {
int i = 0;
char c;
while((c = getchar()) != '\n' && i <= (nchars-1)) {
str[i] = c;
i++;
}
str[i] = '\0';
printf("%s %d\n", str, (int)strlen(str));
}

little change to above answers,Try this it is not giving any "buffer full error"
#include<stdio.h>
#include<string.h>
void getinput(char str1[],int s){
int i=0;
printf("inside fn\n");
char c;
while((c=getchar())!=EOF && i<=(s-1))
{ str1[i++]=c;
}
str1[i]='\0';}
void main()
{ int size;
printf("enter the no. of characters \n");
scanf("%d", &size);
char str1[size+1];
getinput(str1,size);
printf("%s \n",str1);
}

Related

C: Program skips next input

My program skips the next input after 1 pass through it. I have read the threads on removing the newline character that fgets has, but nothing that was suggested worked. Is there anything that would work with microsoft visual studio? The best suggestion was "words[strcspn(words, "\r\n")] = 0;" and this did not remove the new line, unless I am formatting it incorrectly. I am not allowed to use the strtok function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 50
#define STOP "quit\n"
char *copywords(char *dest, const char *source, size_t n);
int main(void)
{
char words[50];
char newwords[50];
size_t num;
for (;;) {
printf("\nType a word, or type 'quit' to quit: ");
(fgets(words, SIZE, stdin));
if (strcmp(words, STOP) == 0) {
printf("Good bye!\n");
return 0;
}
printf("Type the # of chars to copy: ");
scanf_s("%d", &num);
copywords(newwords, words, num);
printf("The word was %s\n", words);
printf("and the copied word is %s", newwords);
}
}
char *copywords(char *dest, const char *source, size_t n) {
size_t i;
for (i = 0; i < n && source[i] != '\0'; i++) {
dest[i] = source[i];
}
dest[i] = '\0';
return dest;
}
The problem is that you leave the \n on the input when you call scanf. i.e. the user types number[return]. You read the number. When you loop around and call fgets agains the return is still waiting to be read so thats what fgets gets and it returns immediately.
I would probably just call fgets the second time you want to read input as well and then use sscanf to read from the string. i.e.
printf("Type the # of chars to copy: ");
fgets(buffer, ...)
sscanf(buffer, "%d", ...)
As an aside I would also say to check return values as it is easy for fgets or *scanf to fail.
My program skips the next input after 1 pass through it.
If I understand you correctly, the problem is that scanf_s (which I assume is like the C standard's scanf) will read the digits into num, but scanf won't remove the following newline from stdin, and so in the next iteration of the loop fgets will see that newline and behave as if it had seen a blank line.
I have usually avoided scanf for this reason and instead read a line into a buffer and then parse it. For example:
char buf[50];
...
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
(I'd also recommend adding a whole lot more error checking throughout.)
Here's a straightforward solution.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 50
#define STOP "quit\n"
char *copywords(char *dest, const char *source, size_t n);
int main(void)
{
char words[50];
char newwords[50];
size_t num, run = 0;
for (;;) {
printf("\nType a word, or type 'quit' to quit: ");
if(run)
getchar();
(fgets(words, SIZE, stdin));
if (strcmp(words, STOP) == 0) {
printf("Good bye!\n");
return 0;
}
printf("Type the # of chars to copy: ");
scanf("%d", &num);
copywords(newwords, words, num);
printf("The word was %s\n", words);
printf("and the copied word is %s", newwords);
run = 1;
}
}
char *copywords(char *dest, const char *source, size_t n) {
size_t i;
for (i = 0; i < n && source[i] != '\0'; i++) {
dest[i] = source[i];
}
dest[i] = '\0';
return dest;
}
Since we know there will be an extra '\n' character left in the stream due to the scanf, just take it out.

Saving strings to structs using gets()? [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 6 years ago.
I'm running into some problems in saving a string - a name, for example - into a struct field. I've used gets() and fgets() both, but fgets() isn't working properly either.
I never get the chance to input the first employee name; it skips straight to the employee code and then skips the address too. For some reason, when inputting the second employee, I get to input both the name and code, and then it skips the address again.
Anyone know what I'm doing wrong?
#include <stdio.h>
typedef struct {
char name[150];
int code;
char add[300];
} tEmployee;
int main()
{
printf("How many employees would you like to register?\n");
int n;
scanf("%i", &n);
tEmployee employee[n];
for (int i = 0; i < n; i++)
{
printf("Name: ");
gets(employee[i].name);
printf("Code: ");
scanf("%i", &employee[i].code);
printf("Address: ");
gets(employee[i].add);
printf("%s\n", employee[i].name);
printf("%i\n", employee[i].code);
printf("%s\n", employee[i].add);
}
return 0;
}
The C library input routines aren't consistent about the way they handle newline (\n). Some read it as part of the input, some don't. Since scanf() gets what it needs before the newline, it has no reason to read it in so we have to so explicitly to clear it out of the buffer before our next input. There are different techniques but just calling getchar() works for this example.
Also, since gets() is considered unsafe, and leaves a newline dangling on the end of your input, I've added a custom my_gets() wrapper that fixes both issues:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[150];
int code;
char add[300];
} tEmployee;
char *my_gets(char *str, int size)
{
char *pos;
char *result = fgets(str, size, stdin);
if (result != NULL && (pos = strchr(str, '\n')) != NULL)
*pos = '\0';
return result;
}
int main()
{
int n;
printf("How many employees would you like to register?\n");
scanf("%i", &n);
getchar(); // eat newline \n
tEmployee employee[n];
for (int i = 0; i < n; i++)
{
printf("Name: ");
my_gets(employee[i].name, 150);
printf("Code: ");
scanf("%i", &employee[i].code);
getchar(); // eat newline \n
printf("Address: ");
my_gets(employee[i].add, 300);
printf("%s\n", employee[i].name);
printf("%i\n", employee[i].code);
printf("%s\n", employee[i].add);
}
return 0;
}
You could make a similar wrapper function for your specific use of scanf() that eats the extra newline for you so you don't have to worry about it everytime you call that function for input.
It's your mixed use of gets and scanf. I've faced similar problem in C++, when I mixed the use of std::cin and >> operator and std::getline function.
Also, gets is deprecated, don't use it...
Anyway, if you really want to use the both, then you should "flush" stdin each time you use scanf, or the next time you read stdin you will read the rest of it till the end of line (the \n).
One way to do it, is to read till the end of line after each scanf:
/* define the function */
void flush()
{
while (getchar() != '\n');
}
Then use it in your code as follow:
printf("How many employees would you like to register?\n");
int n;
scanf("%i", &n);
flush();
tEmployee employee[n];
for (int i = 0; i < n; i++)
{
printf("Name: ");
gets(employee[i].name);
printf("Code: ");
scanf("%i", &employee[i].code);
flush();
printf("Address: ");
gets(employee[i].add);
printf("%s\n", employee[i].name);
printf("%i\n", employee[i].code);
printf("%s\n", employee[i].add);
}
return 0;
Try this:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[150];
int32_t code;
char add[300];
} tEmployee;
typedef uint_fast8_t bool_t;
/*****************************************************************************
* flush stdin... this should be standard but somewhy you need to reinvent
* it all the time...
*****************************************************************************/
static inline void flush_stdin()
{
char ch;
do {
ch = getchar();
} while ((ch != '\n') && (ch != EOF));
}
/*****************************************************************************
* reads a line of text from a stream.
*****************************************************************************/
static inline bool_t xio_fgetline(FILE *stream, char *linebuf, size_t szline)
{
fgets(linebuf, szline, stream);
// find last character.
char *lc = linebuf + strlen(linebuf) - 1;
// the only case when lc is a null is if the program memory
// has been altered. In this case, it should crash anyway.
// therefore I skip a nullcheck before chomping.
// chomp linebuf.
if (*lc == '\n') {
*lc = 0;
}
// string is {0} after chomping.
if (strlen(linebuf) == 0) {
return 0;
}
return 1;
}
/*****************************************************************************
* reads a line of text from stdin.
*****************************************************************************/
static inline bool_t xio_getline(char *linebuf, size_t szline)
{
return (xio_fgetline(stdin, linebuf, szline));
}
int main(int argc, char **argv)
{
int32_t n;
tEmployee *employee = (tEmployee *)0;
printf("How many employees would you like to register?\n");
scanf("%i", &n);
flush_stdin();
employee = (tEmployee *)malloc(n * sizeof(tEmployee));
for (int32_t i = 0; i < n; ++i) {
printf("Name: ");
xio_getline(employee[i].name, sizeof(employee[i].name));
printf("Code: ");
scanf("%i", &employee[i].code);
flush_stdin();
printf("Address: ");
xio_getline(employee[i].add, sizeof(employee[i].add));
printf("%s\n", employee[i].name);
printf("%i\n", employee[i].code);
printf("%s\n", employee[i].add);
}
free(employee);
return 0;
}

Replace the usage of gets with getchar

I currently have a homework assignment and I used gets.
The professor said I should be using getchar instead.
What is the difference?
How would I change my code to use getchar? I can't seem to get it right.
code:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
int main() {
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1) break;
}
}
int getword(char *w) {
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n"); //user input
gets(str);
for(i = 0; str[i] != '\0' && str[i] !=EOF; i++){
if(str[i] != ' '){
charCount++;
} else {
str[i] = '\0'; //Terminate str
i = -1; //idk what this is even doing?
break; //Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount); //output
strcpy(w, str);
// return charCount;
return strlen(w); //not sure what i should be returning.... they both work
}
gets() was supposed to get a string from the input and store it into the supplied argument. However, due to lack of preliminary validation on the input length, it is vulnerable to buffer overflow.
A better choice is fgets().
However, coming to the usage of getchar() part, it reads one char at a time. So basically, you have to keep reading from the standard input one by one, using a loop, until you reach a newline (or EOF) which marks the end of expected input.
As you read a character (with optional validation), you can keep on storing them in str so that, when the input loop ends, you have the input string ready in str.
Don't forget to null terminate str, just in case.

Using scanf for char array in while loop

I am new to C programming.
I was curious as to see how much I have learnt C.
Therefore I thought of creating a program in which I could simply create a file and write in it.
The name of the file, I thought, should be less that 100 chars. But it doesn't matter if it is a string or one word or a letter.
I couldn't complete because I was stuck on fact that how to input a string for a file name(eg, Project work, New Doc1, etc)
So I wrote this;
int main()
{
int a = 0;
while(a != 5)
{
puts("Put a number: ");
scanf("%i", &a);
if(a == 1)
{
char name[30];
printf("Put a name: ->>");
for(int i = 0;i < 31 && name[i] != '\n';i++)
{
name[i] = getchar();
}
char ex[50] = ".txt";
strcat(name,ex);
printf("%s",name);
}
}
return 0;
}
The problem is while inputting the name, it doesn't stop at the next (when I press enter) and some how it is not printing the right file name either.
There's a lot of problems with you approach.
It's not good to mix scanf with another input primitives, you must flush stdin from any remaining characters.
Any string must end in '\0' in order to mark that string as complete. So you must reserve space to this character.
When you concat you must obey the limit of the string.
If you use printf, the string will be only displayed after flushing the stdout (when you put '\n' in the end of the string, flush is done)
Try this:
#include <stdio.h>
#include <string.h>
int main()
{
int a = 0;
while(a != 5)
{
int ch;
puts("Put a number: ");
scanf("%d", &a);
/* flush any remaining characters */
while ((ch=getchar()) != EOF && ch != '\n'); /* issue 1 */
if(a == 1)
{
int i = 0;
char name[30];
printf("Put a name: ->>");
fflush(stdout); /* issue 4 */
while ((ch=getchar()) != EOF && ch != '\n' && i < 25) /* issue 3 */
name[i++] = ch;
name[i] = '\0'; /* issue 2 */
/* flush any remaining characters [if input > 25 chars] */
if (ch != EOF && ch != '\n') while ((ch=getchar()) != EOF && ch != '\n');
char ex[50] = ".txt";
strcat(name,ex); /* issue 3 */
printf("%s\n",name);
}
}
return 0;
}
Also, consider use getline and atoi instead of getchar and scanf
#include<stdio.h>
main()
{
static char stop_char='y';
char input=0;
do{
printf("please input a character\n");
scanf("\n%c",&input);
}while(input!=stop_char);
}

Suggest an alternative for gets() function, using gcc compiler

Trying to input more than a single string in my program's strings array, for that used :
scanf("%80[^\r\n]", strings[i]);
fgets(string[i], MAXLEN, stdin);
a custom made function was also used:
int getString(char s[]) {
char ch;
int i=0;
while( (ch = getchar()) != '\n' && ch != EOF ) {
s[i] = ch;
++i;
}
s[i] = '\0';
fflush(stdin);
return i;
}
but unable to get input with more than one string each including white spaces
function gets() used to work earlier for me but since it is deprecated no alternative can be found
This is where it was used :
int getString(char s[]) {
char ch;
int i=0;
while( (ch = getchar()) != '\n' && ch != EOF ) {
s[i] = ch;
++i;
}
s[i] = '\0';
fflush(stdin);
return i;
}
struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
double price;
} data[5];
int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");
int i=0;
while(i < 5) {
printf("Input vechile Type : \n");
fgets(data[i].vechileType, MAXLEN, stdin);
printf("Input begin month : \n");
scanf("%d", &data[i].begin_month);
printf("Input end monhth : \n");
scanf("%d", &data[i].end_month);
printf("Input price : \n");
scanf("%lf", &data[i].price);
++i;
}
printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);
i=0;
while(i < 5) {
if (strcmp(vech,data[i].vechileType) == 0)
{
printf("vechileType: %s\n", data[i].vechileType);
printf("Begin month: %d\n", data[i].begin_month);
printf("End month: %d\n", data[i].end_month);
printf("Price : %lf\n", data[i].price);
}
++i;
}
return 0;
}
It skips the next input to string statement during run time, "seems to"
Your problem is really not a gets() issue.
None of the scanf("%d", ...) and scanf("%lf", ...) consume the '\n' after the number and thus contribute to your issue. It is the next read of stdin to take in the '\n'. So when the next car type is read, it gets the lingering '\n'. Your 2nd car type ends up being "\n".
Use of fgets(data[i].vechileType, MAXLEN, stdin); puts a '\n' in data[i].vechileType. You likely do not want this. Your former use of gets() consumed, but did not put the '\n' in its return.
I long ago gave up doing user input with scanf() due to these subtle issues.
Recommend to separate input from parsing, use fgets() and then sscanf(). Example:
char number[80];
if (fgets(number, sizeof(number), stdin)) {
sscanf(number, "%d", &x)
Your implementation of a gets() replacement differs as follows
1) It does not return s (or NULL or error/eof).
2) It does not set eof indicator on eof.
3) Should getchar() return a '\0', your while loop errantly continues.
Recommend that if you must replace gets(), do so via fgets().
#define My_gets_N (1024 /* Some BA number */)
char *My_gets(char * str) {
char buffer[My_gets_N];
char *retval = fgets(buffer, sizeof(My_gets_N), stdin);
if (retval) {
int l = strlen(buffer);
/* fgets() saves '\n', but gets() does not */
if ((l > 0) && (buffer[l-1] == '\n')) {
l--;
}
memcpy(str, buffer, l);
str[l] = '\0';
return str;
}
else {
return 0;
}
}
If you replacement solution needs to deal with string length > the fixed My_gets_N, other coding is needed.
You must be more specific about what went wrong with the fgets() approach, that's the one I would recommend and it does work.
Note that fgets() will input the entire line, including linefeed/carriage returns at the end, so you might need to clean those off if they're undesirable to keep.
I don't understand how gets() worked for you, despite the warning that practically every C book post K&R gives, as it's not only deprecated, but extremely dangerous to use. Like the others have said, fgets() would definitely work if you used it correctly.
Instead of replacing all the instances of uses of gets with fgets. Use following Macros:
#define TRUNCATE_NULL(strText) \
 { \
   int _strlen = strlen(strText); \
   if (_strlen > 0 && strText[_strlen - 1] == '\n') strText[_strlen - 1] = '\0'; \
   else while(fgetc(stdin)!='\n'); \
 }
#define gets(strText) fgets(strText, sizeof(strText), stdin); TRUNCATE_NULL(strText);
Why use fgets?
Because it is more secure than gets.
Is gets really insecure?
Yes. It is greedy indeed, it will accept as much food as you give, even if it can not eat.
So technically, as #halfer rightly commented below,
with the use of gets, program is prone to buffer overflow.
How ?
char name[5];
gets(name);
Now provide input of more than 5 characters, it will accept it. This would overwrite data from memory, which should not be overwritten this way.
Ok with fgets, but why use TRUNCATE_NULL macro ?
fgets is not perfect either. it will accept \n (Enter) as character to be placed in input name.So to remove unnecessary \n, and to make sure expected functionality of gets is achieved we can use it.
Actually, there you can use while((getchar())!='\n'); to avoid such type of problem and one thing there is no need to use of fflush(stdin) function.
Here's code you can use
#include<stdio.h>
#include<string.h>
#define MAXLEN 50
int getString(char s[])
{
char ch;
int i=0;
while( (ch = getchar()) != '\n' && ch != EOF )
{
s[i] = ch;
++i;
}
s[i] = '\0';
return i;
}
struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
double price;
}data[5];
int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");
int i=0;
while(i < 2)
{
printf("Input vechile Type : \n");
fgets(data[i].vechileType, MAXLEN, stdin);
printf("Input begin month : \n");
scanf("%d", &data[i].begin_month);
printf("Input end monhth : \n");
scanf("%d", &data[i].end_month);
printf("Input price : \n");
scanf("%lf", &data[i].price);
while((getchar())!='\n');
++i;
}
printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);
i=0;
while(i < 2)
{
if (strcmp(vech,data[i].vechileType) == 0)
{
printf("vechileType: %s\n", data[i].vechileType);
printf("Begin month: %d\n", data[i].begin_month);
printf("End month: %d\n", data[i].end_month);
printf("Price : %lf\n", data[i].price);
}
++i;
}
return 0;
}
I hope this will help you.....

Resources