Check if input is a number [duplicate] - c

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().

Related

C Program Crashes in Visual Studio

I am getting this error whenever I run my code in visual Studio:
#include <stdio.h>
#include <ctype.h>
int main() {
char username[10];
printf("Enter Username: ");
scanf_s("%[^\n]", &username);
while (isupper(username)) {
if (username == '-') {
printf("Username cannot contain UpperCase Letters");
}
}
}
Error Image
I don't think you can pass whole array to isupper. Also if you don't want to return anything instead of int main() use void main() or just return 0 in the end or when you want to end after your program executed successfully. As for using scan_s or scanf or getline or whatever I won't say anything because its a different matter and your syntax of scanf_s is certainly wrong.
Also following code will not check for any buffer overflow (not a good practice, you will see even though we gave size 20 char array, this code will work even for larger input which is certainly not a good thing). So you can either limit the size of input or better to read an entire line via fgets() (or getline() if available) and parse the string yourself.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char username[20];
printf("Enter Username: ");
// scanf("%[^\n]", username); <--- Instead of this
scanf_s("%20c", username, 20); // <----Try Using this
int i=0;
while (i<strlen(username)) {
if (isupper(username[i])) {
printf("Username cannot contain UpperCase Letters\n");
return 0;
}
i++;
}
return 0;
}
My first guess would be that your while is an endless loop, try to do it like this:
int i;
for(i=0; i<strlen(username);i++){
if(isupper(username[i])){
printf("Username cannot contain UpperCase Letters");
}
}

Why cant the loop be terminated in my code?

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

Why is the value of my strcmp not equal to 0 or invalid?

I am still new to programming and there are a lot of things I still don't know but I'd like to ask why my if statement doesn't seem to be working properly. It seems the value
of strcmp(bookName, tolower(searchedName)) when the variable searchedName = "introduction to c" is not 0.
Why is this?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
printf("Enter the book you are searching for: ");
scanf("%s", &searchedName);
if (strcmp(bookName, tolower(searchedName)) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}
tolower() is for converting characters, not strings. You will have to apply it to each characters in the string separately.
You don't need & before arrays in this case because arrays in expressions are automatically converted to pointers (except for some case).
%s in scanf() will stop at whitespace character. %[^\n] is useful to read until hitting a newline character.
Try this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
char searchedName_lower[30];
int i;
printf("Enter the book you are searching for: ");
scanf("%[^\n]", searchedName);
i = 0;
do {
searchedName_lower[i] = tolower((unsigned char)searchedName[i]);
} while (searchedName[i++] != '\0');
if (strcmp(bookName, searchedName_lower) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}

What is the issue with the following code? [duplicate]

This question already has answers here:
Issue with main arguments handling
(3 answers)
Closed 6 years ago.
I am learning C on my own but this code which seems right to me doesn't works right
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
if ( (name=='luv') || (name='pranav') )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
I want the correct code to run only if I enter name as luv or pranav but instead what is happening is that no matter whatever name i type it is running the code under else and i am not able to figure out the reason.
I am using codeblocks as compiler.
You cannot compare strings using ==, to compare strings, one has to use strcmp()
strcmp() returns 0 when the strings are same, other wise it returns the difference of those two strings,
So essentially, your code would become,
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for the strcmp() function
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
// strings are given inbetween double quotes
// characters are given inbetween single quotes
if ( !(strcmp(name, "luv")) || !(strcmp(name, "pranav")) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
NOTE:
1) Use the standard definition of main()
int main(void) //if no command line arguments.
2) Check the return of functions like scanf().
Lots of mistakes in the code.
I am trying to fix and show:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // to use strcmp
int main(void) // int and void added
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf("%19s", name); // no space before % and 19 to limit input
if ( !strcmp(name,"luv") // " instead of ' , and strcmp with operator !
|| strcmp(name,"pranav") == 0 ) // instead of ! you can use == 0
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
main() is not a standard signature. You should use standard int main(void) unless you have some special reason to use non-standard signature.
'luv' and 'pranav' are multiple-character character constant, which have implementation-defined values. You should use string literals and strcmp() function.
name='pranav' is an assignment, and you cannot assign to what is converted from arrays, so this will emit compile error.
You should limit the length to read in order to avoid buffer overflow.
Try this:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %19s", name);
if ( (strcmp(name, "luv") == 0) || (strcmp(name, "pranav") == 0) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
remove #include <conio.h> and getch(); if they are not supported.
Two problems:
Single quotes are used for character constants, not string constants. You need to use double quotes for those.
Strings can't be compared with ==. What you're actually doing is comparing the address of the first element of name with a character constant. Even if you fixed the quotes on the constant, you'd be comparing the address of name with the address of a string constant, which are not the same. To compare strings, you use strcmp, which compares each character in the string.
So what you want is this:
if ( (strcmp(name,"luv") == 0) || (strcmp(name,"pranav") == 0) )
You'll also need to #include <string.h> to use strcmp.

c program not taking input properly and producding wrong output

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*-1;
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Input to the code is in the form:
t
n x
some_string_having_A_and_B
Sample:
1
3 10
ABA
expected output
-10
actual output
10
This code gives -10 if number of B is odd and 10 if number of B is even. I know the correct and optimal way of writing the program but I can't figure out, why this code is producing wrong ouput.
The first scanf("%c") reads the previous ENTER in the input stream.
Suggestion for fast fix: use a space inside the specification to have scanf ignore whitespace (Enter is whitespace).
Try
if (scanf(" %c", &st[j]) != 1) /* error */;
// ^ ignore whitespace
Suggestion for better fix: read all user input with fgets().
char line[100];
...
fgets(line, sizeof line, stdin);
if (sscanf(line, "%c", &st[j]) != 1) /* error */;
if(st[j]=='B')
x=x*-1;// you need to put bracket here.on -1
//correct form is x=x*(-1)
}
//corrected code starts from here
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*(-1);// you need to put bracket here.on -1
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}

Resources