wrapper function in fgets() - c

I seek for an expert in c programming. Thanks in advance.
Example:
#include <stdio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
char name[100][52],selection[2]="Y";
int x,nname=1;
float sales;
do
{
printf("Enter name: ");
fflush(stdin);
fgets(name[nname],51,stdin); // i need put a wrapper in here
printf("Enter sales: ");
scanf("%f",&sales);
if (sales<1000)
printf("%s\tgood\n",name[nname++]);
else
printf("%s\tvry good\n",name[nname++]);
printf("Enter another name?(Y/N)");
fflush(stdin);
fgets(selection,2,stdin);
*selection=toupper(*selection);
}while(nname<=100 && *selection=='Y');
for(x=1;x<nname;x++)
printf("%s\n",name[x]); // want print the result without(newline) /n
printf("END\n");
system("pause");
}
How do I print the names without being separated by new lines?

I compiled it with GCC 4.4.1 - MinGW and it works fine.
It launched only a warning. This is the result:
warning: return type of 'main' is not 'int'|
||=== Build finished: 0 errors, 1 warnings ===|
Now it works as you expect.
#include <stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include <string.h> // strlen()
void main() {
char name[100][52],selection[2]="Y";
int x,nname=1;
float sales;
do {
printf("Enter name: ");
fflush(stdin);
fgets(name[nname],51,stdin); // i need put a wrapper in here
for (x=0; x<strlen(name[nname]); x++){ // this will discarge the \n
if (name[nname][x] == '\n')
name[nname][x] = '\0';
}
printf("Enter sales: ");
scanf("%f",&sales);
if (sales<1000)
printf("%s\tgood\n",name[nname++]);
else
printf("%s\tvry good\n",name[nname++]);
printf("Enter another name?(Y/N)");
fflush(stdin);
fgets(selection,2,stdin);
*selection=toupper(*selection);
} while(nname<=100 && *selection=='Y');
for(x=1; x<nname; x++)
printf("%s ",name[x]); // want print the result without(newline) /n
printf("\nEND\n"); // inserted \n before END
system("pause");
}

Just use
printf("%s ", name[x]);
instead of
printf("%s\n", name[x]);
The \n character is creating the new lines.
Edit
fgets apparently reads newlines into the buffer - you can strip the newline with
name[nname][strlen(name[nname])-2] = '\0';

Related

C: Any Alternative way to get each of string element without using conio.h?

I am trying to write a program to access the name from user and print each of element and it address but can't figure out what happen to my code. If Gcc compiler not support Conio.h library so what should i do? Can I write a program without using conio.h library?.
Please explain it
Here is my code:
//Write a program to find each of string element and it location
#include <stdio.h>
#include<conio.h>
int main(){
char name[10];
int i = 0;
printf("Please enter your name: ");
scanf("%s", name);
while(name[i] != '\0'){
printf("%c is located at %u", name[i], &name[i]);
i++;
}
getch();
return 0;
}
Output: No such file or directory
complination terminated
You should actually display a pointer using the %p format specifier. For more information Correct format specifier to print pointer or address?
#include <stdio.h>
int main(){
char name[10];
int i = 0;
printf("Please enter your name: ");
scanf("%s", name);
while(name[i] != '\0'){
printf("%c is located at %p", name[i], &name[i]);
i++;
}
return 0;
}
Edit: As mentioned in the comment by #David, you should check the return value of scanf also.
if (scanf ("%9s", name) != 1){
fputs ("error: name invalid or EOF\n", stderr);
return 1; }

fflush(stdin) with VS2013 and VS2015 [duplicate]

I can't seem to figure out what's wrong with this code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
#define TRUE 1
#define FALSE 0
char sect_cat;
char customer_name[MAX];
char customer_number[MAX]; /* error handling is easier */
int prev_unit = 0;
int current_unit = 0;
int consumed = 0;
int set = FALSE;
float init_bill;
float tax;
float total_bill;
void get_userinfo()
{
printf("Enter sector category: ");
scanf("%c", &sect_cat);
printf("Enter customer name: ");
fflush(stdin);
scanf("%sn", &customer_name);
set = FALSE;
while (set == FALSE)
{
printf("Enter customer number: ");
fflush(stdin);
scanf("%s", customer_number);
int i;
int error;
for (i=0, error=0; i<strlen(customer_number); i++)
{
if (isdigit(customer_number[i]))
{
}
else
{
error = 1;
}
}
if (error == 0)
{
set = TRUE;
}
else
printf("ERROR: Only numbers are allowed\n");
}
printf("Enter previous unit: ");
fflush(stdin);
scanf("%d", &prev_unit);
set = FALSE;
while (set == FALSE)
{
printf("Enter current unit: ");
fflush(stdin);
scanf("%d", &current_unit);
if (prev_unit > current_unit)
{
printf("ERROR: Current unit must be larger than previous unit\n");
}
else
set = TRUE;
}
consumed = current_unit - prev_unit;
}
int main()
{
/* Introduce program to users */
printf("\nThis program computes your electric bill based on these sector categories\n\n");
printf("\tResidential(R)\n");
printf("\tIndustrial(I)\n");
printf("\tCommercial(C)\n\n");
printf("Press any key to continue...");
fflush(stdin);
getchar();
#################### edit
Applying templatetypedef's solution, the program now waits for user input for the customer_name. However entering a string with a space leads to an error, and the program assumes that the word after the space is input for the next prompt.
Enter sector category: r
Enter customer name: George of the Jungle
Enter customer number: ERROR: Only numbers are allowed
Enter customer number: ERROR: Only numbers are allowed
Enter customer number:
The fflush function does not flush data out of an input stream; it is instead used to push data buffered in an output stream to the destination. This is documented here. As seen in this earlier SO question, trying to use fflush(stdin) leads to undefined behavior, so it's best to avoid it.
If you want to eat the newline from the return character entered when the user finished typing in their character, instead consider the following:
scanf("%c%*c", &sect_cat);
This will eat the newline rather than leaving it in stdin.
Hope this helps!
I think that you meant to write fflush(stdout) instead of fflush(stdin).
fflush should work with an output stream, see docs here

Getting specific # of characters

I want to get only 2 characters in my program. I tried fgets but I can get it to work. How do you suggest that I implement this? Or is there any alternative?
char code[2];
printf("Enter code: \n");
scanf("%s", code);`
I want to limit the number of characters that can be entered to two.
To read two characters and ignore white space you can do:
#include <stdio.h>
int main() {
char code[2];
printf("Enter code:\n");
if (scanf(" %c %c", &code[0], &code[1]) == 2) {
printf("successfully read '%c' and '%c'\n", code[0], code[1]);
}
return 0;
}
to not ignore white space use "%c%c" as the format.
Try this code
#include<stdio.h>
#include<conio.h>
void main()
{
char code;
clrscr();
printf("enter the code\n");
scanf("%2s",code);
printf("%s",code);
getch();
}

fflush(stdin) function does not work

I can't seem to figure out what's wrong with this code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
#define TRUE 1
#define FALSE 0
char sect_cat;
char customer_name[MAX];
char customer_number[MAX]; /* error handling is easier */
int prev_unit = 0;
int current_unit = 0;
int consumed = 0;
int set = FALSE;
float init_bill;
float tax;
float total_bill;
void get_userinfo()
{
printf("Enter sector category: ");
scanf("%c", &sect_cat);
printf("Enter customer name: ");
fflush(stdin);
scanf("%sn", &customer_name);
set = FALSE;
while (set == FALSE)
{
printf("Enter customer number: ");
fflush(stdin);
scanf("%s", customer_number);
int i;
int error;
for (i=0, error=0; i<strlen(customer_number); i++)
{
if (isdigit(customer_number[i]))
{
}
else
{
error = 1;
}
}
if (error == 0)
{
set = TRUE;
}
else
printf("ERROR: Only numbers are allowed\n");
}
printf("Enter previous unit: ");
fflush(stdin);
scanf("%d", &prev_unit);
set = FALSE;
while (set == FALSE)
{
printf("Enter current unit: ");
fflush(stdin);
scanf("%d", &current_unit);
if (prev_unit > current_unit)
{
printf("ERROR: Current unit must be larger than previous unit\n");
}
else
set = TRUE;
}
consumed = current_unit - prev_unit;
}
int main()
{
/* Introduce program to users */
printf("\nThis program computes your electric bill based on these sector categories\n\n");
printf("\tResidential(R)\n");
printf("\tIndustrial(I)\n");
printf("\tCommercial(C)\n\n");
printf("Press any key to continue...");
fflush(stdin);
getchar();
#################### edit
Applying templatetypedef's solution, the program now waits for user input for the customer_name. However entering a string with a space leads to an error, and the program assumes that the word after the space is input for the next prompt.
Enter sector category: r
Enter customer name: George of the Jungle
Enter customer number: ERROR: Only numbers are allowed
Enter customer number: ERROR: Only numbers are allowed
Enter customer number:
The fflush function does not flush data out of an input stream; it is instead used to push data buffered in an output stream to the destination. This is documented here. As seen in this earlier SO question, trying to use fflush(stdin) leads to undefined behavior, so it's best to avoid it.
If you want to eat the newline from the return character entered when the user finished typing in their character, instead consider the following:
scanf("%c%*c", &sect_cat);
This will eat the newline rather than leaving it in stdin.
Hope this helps!
I think that you meant to write fflush(stdout) instead of fflush(stdin).
fflush should work with an output stream, see docs here

How to format input to only accept integer values

input value 123 -- this value is integer, and valid
input value 1b23a -- this value is invalid
How do I detect which values are valid and not?
Here is my code:
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[5],str2[5];
int num,num1,i;
num=0;
clrscr();
printf("Enter the Number ");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]>=48&&str1[i]<=56)
num=num1*10+(str[i]-48);
else
{
printf("The value is invalid ");
}
}
printf("This Number is %d",num);
getch();
}
Please see this answer regarding use of strtol(). It is a safe way to convert arbitrary input that should be a string representation of an integer, while also saving 'garbage' bytes for additional analysis.
Using it, your code would look something like this:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#ifdef LINUX_VERSION
#include <curses.h>
#else
#include <conio.h>
#endif
#define BUFF_SIZE 1024
int main(void)
{
char str1[BUFF_SIZE], *garbage = NULL;
long num = 0;
printf("Enter the Number ");
scanf("%s",str1);
errno = 0;
num = strtol(str1, &garbage, 0);
if (errno) {
printf("The number is invalid\n");
return 1;
}
printf("You entered the number %ld\n", num);
if (garbage != NULL) {
printf("Additional garbage that was ignored is '%s'\n", garbage);
}
getch();
return 0;
}
This doesn't fix everything that is questionable about what you posted, but it should help you get off to a better start.
Output is:
tpost#tpost-desktop:~$ ./t
Enter the Number 1234abdc
You entered the number 1234
Additional garbage that was ignored is 'abdc'
Compiled via:
gcc -Wall -DLINUX_VERSION -o t t.c -lcurses
I'm not sure what platform you are using, so additional fixes to the code may be needed.
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[5],str2[5];
int num,num1,i;
num=0;
clrscr();
printf("Enter the Number ");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(str1[i]>=48&&str1[i]<=56)
num=num1*10+(str[i]-48);
else
{
printf("The value is invalid ");
}
}
printf("This Number is %d",num);
getch();
}
One way is to use sscanf and check that there are no characters following the number. This is done most easily by adding a %c on the end and testing the return code, like this:
const char *yourString = ...;
int theValue, dummy;
if (sscanf(yourString, "%d%c", &theValue, &dummy) == 1) {
// Was a pure number, parsed into 'theValue'
} else {
// Either no number or had junk after it
}

Resources