I'm making a function to validate an integer within a domain and ask the user to type again if the number is out of range or if they typed in a character(or string of characters) or if they typed in more than just an integer. The code looks like this:
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
//\input stream clear function\*
void clear()
{
char c;
while((c=getchar())!='\n'&&(c=getchar())!=EOF){}
}
//getchar(char str[], min, max)
int GetInt(char msg[], int min, int max)
{
int value;
int rc;
char ovflow;
while (true)
{
printf("%s", msg);
rc = scanf("%d%c",&value,&ovflow);
if(rc == 0 || rc == 1)
{
printf("**No input accepted!**\n\n");
clear();
}
else if(ovflow != '\n')
{
printf("**Trailing characters!**\n\n");
clear();
}
else if(value < min || value > max)
{
printf("**Out of range!**\n\n");
}
else break;
}
return value;
}
int main()
{
int value=GetInt("enter value: ",2,20);
return 0;
}
Things work fine but when I typed in "something", the program froze until I press another Enter. It should look like this:
It froze if I typed in some certain string
It should still print the printf("%s", msg); and immediately prompt for more input. I could guess it was because of clear() function but whatever I tried, I could not fix it. I would be thankful if you can help me with this.
The answer is to just call getchar() once. ex:
((c = getchar()) != '\n' && c != EOF) {}
From a comment by Johnny Mopp
Related
#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine.
Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().
First of all #define max generates a warning "macro redefinition", so change that.
The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r
The third problem is that instead of incrementing the pointers, you are incrementing what they point to.
Here is the corrected code:
#include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name, char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name, input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.
This a reverse string code but the loop cant be terminated and keeps taking input
How can I terminate it
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i;
do {
gets(str);
for (i = (strlen(str) - 1); i > -1; i--) {
printf("%c", str[i]);
}
printf("\n");
} while (str[0] != '\0');
return 0;
add str[0]='\0'; before gets and its done. this is because making a loop termination and to get out of the loop after clicking enter.
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i,lenh;
do{
str[0]='\0';
gets(str);
lenh=strlen(str);
for(i=lenh-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}while(str[0]!='\0');
return 0;
}
now, there are a few points (answer code below)
Basically, you are printing hand-to-hand with input, while the question states of a multi line input. So, first you have to take all the inputs and then output will be shown.
Your original code does not keep taking input as you have said. Question says the last string is empty string. You press enter in empty string, your above code will terminate.
Remember Last Input String Should be Empty, that's termination condition
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char stringArray[50][100]={0};
int k,m,count=0,i=0,j=0;
do {
fgets(str,100,stdin);
k=strlen(str);
for(m=0;m<k-1;m++){
stringArray[count][k-m-2]=str[m];
}
count++;
}
while (str[0] != '\n');
for(i=0; i<count; i++){
for(j=0;stringArray[i][j]!=0;j++){
printf("%c",stringArray[i][j]);
}
if(i<count-1){
printf("\n");}
}
return 0;
}
sample input
Hello team Loop
Welcome
sample output
pooL maet olleH
emocleW
This question already has answers here:
Check if input is integer type in C
(16 answers)
Closed 5 years ago.
I have a bit of code that is supposed to get numbers from input until EOF and put them inside an array.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
while(scanf("%d",&i)!=EOF){
numbers[m]=i;
m++;
}
}
My problem is that I need to check if the input is valid (if it is a number). If it is not a number I need to print out a message that says something along the lines "Wrong input" and end the program.
Can somebody please help me?
PS. I know that this question has been asked several time, I have googled, but I have not been able to figure out from the answers how to adapt the code to my situation. So, sorry if the question seems redundant.
scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf will return 1.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
int itemsRead = 0;
while(itemsRead = scanf("%d",&i) != EOF){
if (itemsRead != 1)
{
printf("Wrong input");
return 0;
}
numbers[m]=i;
m++;
}
}
Shortening #gssamaras code, you can have something simpler, like this
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
int numbers[250000],i,m=0;
char temp;
while(scanf("%c",&temp)!=EOF)
{
if(!isdigit(temp)))
{
printf("Wrong input");
break;
}
numbers[m]=atoi(temp);
m++;
}
}
You need to read the input as a string, validate that its context is actually a number, and then assign it to the array's cell, like this:
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#define MAXINPUT 100
int main() {
int numbers[250000],m=0;
char input[MAXINPUT] = "";
while(scanf ("%s", input)!=EOF) {
for (size_t i = 0; i < strlen(input); i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
// here we know that 'input' is a number
numbers[m] = atoi (input);
m++;
}
return 0;
}
PS: I would use fgets() instead of scanf().
How do I put isalpha and isdigit in a while(1) loop?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i;
char type[256];
printf("You can type a number or a word. Type exit to exit! \n");
printf("Type: ");
fgets (type, 256, stdin);
if (isalpha(type[i]))
{
printf("Typed text: %s\n", type);
if((strcmp(type,"exit\n") == 0))
{
printf("Exiting...\n");
exit(1);
}
}
else if (isdigit(type[i]))
{
printf("Typed number: %s\n", type);
}
else
{
printf("Typed: %s\n", type);
printf("Its not a letter or number...?!\n");
}
}
I tried adding while(1) at the start at the code and close it at the end of code, but as soon as I enter number or letter the console crashes... Could someone please help me with this?
Your problem is not a loop problem, you need to give a value to i , as it is undefined and you get a nice crash. Please replace
int i;
with
int i=0;
#include "stdafx.h"
#include <stdlib.h>
void main()
{
char buffer[20];
int num;
printf("Please enter a number\n");
fgets(buffer, 20, stdin);
num = atoi(buffer);
if(num == '\0')
{
printf("Error Message!");
}
else
{
printf("\n\nThe number entered is %d", num);
}
getchar();
}
The above code accepts a number in the form of a string and converts it to integer using atoi. If the user inputs a decimal number, only the bit before the decimal is accepted. Moreover, if the user enters a letter, it returns 0.
Now, I have two queries:
i) I want the program to detect if the user entered a number with decimal point and output an error message. I don't want it to take the part before the decimal point. I want it to recognize that the input is invalid.
ii) If atoi returns 0 in case there are letters, how can I validate it since the user can enter the number 0 as well?
Thanks.
atoi is not suitable for error checking. Use strtol or strtoul instead.
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
long int result;
char *pend;
errno = 0;
result = strtol (buffer, &pend, 10);
if (result == LONG_MIN && errno != 0)
{
/* Underflow. */
}
if (result == LONG_MAX && errno != 0)
{
/* Overflow. */
}
if (*pend != '\0')
{
/* Integer followed by some stuff (floating-point number for instance). */
}
There is the isdigit function that can help you check each character:
#include <ctype.h>
/* ... */
for (i=0; buffer[i]; i++) {
if (!isdigit(buffer[i])) {
printf("Bad\n");
break;
}
}