Store numbers as a string - c

I'm new in programming and I'm facing the problem where the program has to ask the user to enter as much numbers as he wants and store them in a variable, then print all the digits until a 0 is found.
The only thing i could think of was to store the scanf() in a char*, then try to print all digits until a 0 is found, but i end up with a segmentation faults...
here's my code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]){
char entry[50];
printf("Enter a number !\n");
scanf("%c", &entry); // maybe %d or %s ?
printf("\n");
int i=0;
while (entry[i] != 0){
if (entry[i] !=0){
printf("%c", entry[i] ); // maybe %d with, (int)entry[i] ?
}
i++;
}
return 0;
}
Edit : It works now, had to fix (entry[i] != 0) --> (entry[i] != '0') and the scanf's %c --> %s.

You could read it as string (%s) and compare until the current character is character 0:
while (entry[i] != '0') {
Characters go between single quotes in c.
You could get the same result comparing with the integer 48 as 48 is the ASCII code of 0 and it's how the char is stored internally but it's more readable and easy to understand comparing it to '0'.
And that if inside the while is not necessary as it's going to be always true.

Related

why does the getchar() function not work here?

I'm trying to write C code where it takes in integer inputs, and prints them, unless the newline character ('\n') is entered.
But it never returns the value that I enter.
If I enter 6, I expect it to print 6 but it gives me 54. In fact whatever number I expect, it gives me 48+(my number). Please help!
Here's my code:
#include <stdio.h>
int main(int argc, char *argv[])
{
int counter = 0;
int num;
while (counter <=1)
{
num = getchar();
if (num == '\n')
{
break;
}
counter+=1;
printf("%d", num);
}
return 0;
}
It looks like an ASCII code for your characters is printed.
Use %c to print one character:
printf("%c", num);
Or subtract '0' (the character code of 0) from the value to convert digit characters to the corresponding integer:
printf("%d", num - '0');
That's because you are printing the ascii equivalent of the integer. You can either typecast the input you get, i.e, int(num) after you read it or you can use scanf like this:
int num;
scanf("%d", &num);

Converting user input to an array of characters, and filtering letters from other characters?

#include "stdafx.h"
#include "stdlib.h"
#include <ctype.h>
int num = 0;
int i = 0;
int ch = 0;
int letter_index_in_alphabet(int ch) {
if (isalpha(ch) == true) {
char temp_str[2] = { ch };
num = strtol(temp_str, NULL, 36) - 9;
printf("%d is a letter, with %d as its location in the alphabet!", ch, num);
}
else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 10 letters and numbers: \n");
fgets(input_str, 10, stdin);
for (i == 0; i <= 10; i++) {
ch = input_str[i];
letter_index_in_alphabet(ch);
}
return 0;
}
Hello everyone, this is my first post on SOF! The goal of this program is to read characters from the standard input to EOF. For each character, report if it is a letter. If it is a letter, print out its respective index in the alphabet ('a' or 'A' = 1, 'b' or 'B' = 2..etc). I have been searching some other posts on stackoverflow and this has helped me get this far(using fgets and strtol functions). I have no visible syntax errors when I run this code, but after I enter a string of characters (ex: 567gh3fr) the program crashes.
Basically, I am trying to use 'fgets' to bring each character entered into a string with the appropriate index. Once I have that string, I check each index for a letter and if it is, I print the number assigned to that letter of the alphabet.
Any help or insight into why this isn't working as intended is greatly appreciated, Thanks!
You have a few problems.
First, char input_str[10] is only big enough for the user to enter 9 characters, not 10, because you need to allow one character for the null byte that ends a string.
Second, your loop goes too far. For a string with 10 characters, indexes go up to 9, not 10. It also should stop when it gets to the null byte, since the user might not have entered all 9 characters.
To get the position in the alphabet, you can simply subtract the value of A or a from the value of the character. Use tolower() or toupper() to convert the character to the case that you're going to use. Your method works, but it's overly complicated and confusing.
letter_index_in_alphabet() is declared to return int. But when the character is a letter, it doesn't execute a return statement. I'm not sure why it's supposed to return something, since you never use the return value, but I've changed it to return the position (maybe the caller should be the one that prints the message, so the function just does the calculation).
In the for loop, it should be i = 0 to perform an assignment, not i == 0 which is comparison.
You also shouldn't use global variables so much. And system header files should have <> around them, not "".
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int letter_index_in_alphabet(int ch) {
if (isalpha(ch)) {
int num = tolower(ch) - 'a' + 1;
printf("%d is a letter, with %d as its location in the alphabet!\n", ch, num);
return num;
} else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 9 letters and numbers: \n");
fgets(input_str, sizeof(input_str), stdin);
for (int i = 0; input_str[i]; i++) {
letter_index_in_alphabet(input_str[i]);
}
return 0;
}

Scanning values in C till hit a new-line char, '\n'

How can I scanf() the integer values I enter into an array until I hit enter.
I believe I can use getchar() != '\n'.
but how do I loop through the line ?
Suppose my input is 20 21 2 12 2. I want an array that has all those inputs.
What given functions could I use in order to scan them all in.
You are trying to read integers as characters so once read you need to convert it to integers.
Read the line to a buffer using fgets() then parse the input buffer to get integers.
Store the integers to the array.
The code looks like
char buf[300];
int a[5],i=0;
fgets(buf,sizeof(buf),stdin);
char *p = strtok(buf," ");
while(p != NULL)
{
char *endptr;
a[i] = strtol(p,&endptr,10);
if ((*endptr != '\0') && (isspace(*endptr) == 0))
printf("warning: invalid value detected\n");
else
i++;
p = strtok(NULL," ");
}
You can use the alternative strtol() instead of atoi() to convert string to integer.
PS: Your buf should be large enough to hold the whole line. fgets() read till newline character.
If you use getchar() you obtain digits one by one, so you need
to store them first in the buffer, and when white space comes,
you convert those digits into a number, and store it into array.
here is the explanation of the code I made for you.
1st if statement : if obtained character is a digit, store it in buf
2nd if statement : if obtained character is a white space or EOL and at least 1 digit is stored in buf, convert digits into number and store it in array a.
3rd if statement : if obtained character is not a digit or a white space or a EOL, warns users.
4th if statement : if obtained character is a EOL, end loop.
The code below works fine.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
#define BUFSIZE 50
#define ARRAYSIZE 5
int i,k,a[ARRAYSIZE];
char c,buf[BUFSIZE];
for(i=0,k=0;(i<BUFSIZE)&&(k<ARRAYSIZE);){
c=getchar();
if(isdigit(c)){
buf[i++] = c;
}else if((i>0) && (c==' ' || c=='\n')){
buf[i] = '\0';
a[k++] = atoi(buf);
i=0;
}else if(!(c==' ' || c=='\n')){
printf("warning : invalid value %c is detected\n",c);
i=0;
}
if(c=='\n'){
break;
}
}
printf("input :");
for(i=0;i<ARRAYSIZE;i++){
printf("%d, ",a[i]);
}
printf("\n");
}

How to ignore floating number in scanf("%d")?

If user enters floating number for an integer variable I want to print invalid input. is that possible?
int a;
scanf("%d",&a); // if user enters 4.35 print invalid input
I have tried for characters like this
if(scanf("%d",&a)==1);
else printf("invalid input");
But how to do for floating numbers. If user enters 4.35 it truncates to 4 but I want invalid input.
Since the start of a floating point number with any digits before the decimal point looks like an integer, there is no way to detect this with %d alone.
You might consider reading the whole line with fgets() and then analyzing with sscanf():
int a;
int n;
char line[4096];
if (fgets(line, sizeof(line), stdin) != 0 && sscanf(line, "%d%n", &a, &n) == 1)
...analyze the character at line[n] for validity...
(And yes, I did mean to compare with 1; the %n conversion specifications are not counted in the return value from sscanf() et al.)
One thing that scanf() does which this code does not do is to skip blank lines before the number is entered. If that matters, you have to code a loop to read up to the (non-empty) line, and then parse the non-empty line. You also need to decide how much trailing junk (if any) on the line is tolerated. Are blanks allowed? Tabs? Alpha characters? Punctuation?
You'll have to read it as a double and then check if it is an integer. The best way to check if it is an integer is to use modf, which returns the decimal portion of the double. If there is one you have an error:
double d;
scanf("%lf", &d);
double temp;
if(modf(d, &temp)){
// Handle error for invalid input
}
int a = (int)temp;
This will allow integers or floating point numbers with only 0s after the decimal point such as 54.00000. If you want to consider that as invalid as well, you are better off reading character by character and verifying that each character is between 0 and 9 (ascii 48 to 57).
This can not be done with out reading pass the int to see what stopped the scan.
Classic idiom
char buf[100];
if (fgets(buf, sizeo(buf), stdin) == NULL) {
; // deal with EOF or I/O error
}
int a;
char ch;
if (1 != sscanf(buf, "%d %c", &a, &ch)) {
; // Error: extra non-white space text
}
You can do it using strtol() and strtod() and comparing the end pointers, e.g. this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[100];
char * endptr_n;
char * endptr_d;
long n;
double d;
fgets(buffer, 100, stdin);
n = strtol(buffer, &endptr_n, 10);
if ( endptr_n == buffer ) {
fputs("You didn't enter a number.", stderr);
return EXIT_FAILURE;
}
d = strtod(buffer, &endptr_d);
if ( *endptr_d == '\0' || *endptr_d == '\n' ) {
if ( endptr_d == endptr_n ) {
puts("You entered just a plain integer.");
} else {
puts("You entered a floating point number - invalid.");
}
} else {
puts("You entered garbage after the number - invalid.");
}
return EXIT_SUCCESS;
}
outputs:
paul#local:~/src/c$ ./testint
2
You entered just a plain integer.
paul#local:~/src/c$ ./testint
2.3
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
3e4
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
4e-5
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
423captainpicard
You entered garbage after the number - invalid.
paul#local:~/src/c$
It doesn't use scanf(), but that's a good thing, and it avoids the need to manually check the input following the integer you read.
Obviously, if the only thing on the line is the number, then a lot of this becomes unnecessary, since you can just call strtol() and check *endptr_n immediately, but if there may be other stuff on the line this is how you can do it, e.g. if you want to accept an integer followed by anything non-numeric, but not a floating point followed by the same thing, you can just remove the if ( *endptr_d == '\0' || *endptr_d == '\n' ) logic.
EDIT: updated the code to show the check to *endptr.
This one is bit easier:
#include <stdio.h>
int main()
{
int a;
long double b;
scanf("%f",&b);
a = (int) b;
a == b ? printf("%d\n",a) : printf("Invalid input!");
return 0;
}
Input: 4
Output:
4
Input: 4.35
Output:
Invalid input
Here's an easy way:
#include <stdio.h>
int main(int argc, char **argv) {
int d;
printf("Type something: ");
// make sure you read %d and the next one is '\n'
if( scanf("%d", &d) == 1 && getchar() == '\n' ) {
printf("%d\n", d);
}
return 0;
}
.
$ a.exe
Type something: 312312.4214
$ a.exe
Type something: 2312312
2312312
$ a.exe
Type something: 4324.
$
First of all, there is nothing wrong with scanf. When a user enters a float then they actually type in a number dot number. So, code a scanf to detect that data entry.
main()
{
char c1[2];
int num1;
int nr_nums;
nr_nums = scanf("%d%1[.e0123456789]", &num1, &c1);
if (nr_nums == 1) {printf("\ndata = %d", num1);}
if (nr_nums == 2) {printf("\nInvalid");}
}
Modified this code per another possible data entry format of 1. or 3e-1 as suggested by a comment.
This code gets to the basics of your requirement. It accepts Integer data entry and detects when a float is entered.
If you have your number represented as a string (when you have used fgets) you can run a for loop through it and compare each character to '.'.
One other option I can see follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char mystring[31];
scanf("%30s[0-9]\n", mystring);
int mynumber = atoi(mystring);
printf("here is your integer: %d", mynumber);
getchar();
getchar();
return 0;
}

How to invalidate an input in c

I'm writing a program in C that is suppose to ask the user for a number.
The number has to be greater than zero and cannot have letters before or after the number. (ie: 400 is valid but abc or 400abc or abc400 is not). I can make my program invalidate everything besides 400abc. How would I make it invalidate an input if it starts valid then turns invalid? (I'm about 2 months into an intro to c class so my knowledge is very limited.)
#include<stdio.h>
int check(void);
void clear_input(void);
main()
{
int num;
printf("Please enter a number: ");
num = check();
printf("In Main %d\n", num);
}
int check(void){
int c;
scanf("%d", &c);
while (c < 0){
clear_input();
printf("Invalid, please enter an integer: ");
scanf("%d", &c);
}
return c;
}
void clear_input(void){
char junk;
do{
scanf("%c", &junk);
}while (junk != '\n');
}
You can also check whether ascii value of each char scanned from user input should lie in range 48-57, It will only then be integer value.
strtol can be used to do it, but it takes some extra work.
After running this code:
char *endptr;
int n = strtol(num_text, &endptr, 10);
n will contain the number. But you still have to check that:
1. *endptr=='\0' - this means strtol didn't stop in the middle. In 400abc, endptr will point to abc. You may want to allow trailing whitespace (in this case, check that endptr points to an all-whitespace string.
2. num_text isn't empty. In this case, strtol will return 0, but an empty string isn't a valid number.
Read the input as a line, using fgets.
Check if all characters are numeric.
If not, it's invalid. If yes, use sscanf to get the line into an int.
Check if the int is in the range; you're done.
Scanf with %d will treat the "400abc" as 400, all the trailing characters would be ignored, so there is nothing to worry about.
If you definitely want to treat "400abc" as an invalid input, then maybe you shouldn't use %d in scanf, use %s instead?
One way is to read the whole line as a string and check by yourself if it contains any non-digits.
The other way is reading the integer and then looking into the input using fgetc() to see if the next character after the detected input is valid. Or you could even use the same scanf() for this:
char delim;
if(scanf("%d%c", &c, &delim) == 2 && !isspace(delim))
// the input is invalid
You can read the number in a character array and validate it by checking if all the characters lie in the ascii range 48 to 57 ( '0' to '9' ) .If so your no. is valid otherwise you can safely regard it as invalid input.Here the the demonstration :
#include<stdio.h>
#include<string.h>
int conv( char * word )
{
int ans=0;
int res=0;
for(int i=0;i<strlen(word);i++)
if(word[i]>='0' && word[i]<='9')
ans=(ans*10) + (word[i] - '0');
else
res=-999;
if(res==-999)
return res;
else
return ans;
}
int main()
{
char a[10];
gets(a);
int b=conv(a);
if(b==-999)
printf("Invalid Entry.\n");
else
printf("Success.No is %d.\n",b);
return 0;
}
You can adjust for negatives as well by checking the first character in the word array to be '-' and adjusting the sign accordingly.
This is C99, so compile with -std=c99
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
bool getNum(int *n) {
char c, s[10];
if (!scanf("%9s", s))
return false;
for (int i=0; c=s[i]; i++)
if (!isdigit(c))
return false;
*n = atoi(s);
return true;
}
int main() {
int n;
if (getNum(&n))
printf("you entered %d\n", n);
else
printf("you did not enter a number\n");
}
The following is your check function rewritten to fix your problem, so try this:
int check(void){
int n;
char c;
while (EOF==scanf("%d%c", &n,&c) || n < 0 || !isspace(c)){
clear_input();
printf("Invalid, please enter an integer: ");
}
return n;
}

Resources