This is a program which reads data character by character until it finds a character digit and converts it into an integer.
#include <stdio.h>
int main(void) {
char ch = getchar();
printf("Type some data including a number");
while(ch < '0' || ch > '9') //as long as the character is not a digit.
{
ch = getchar();
}
int num = 0;
while(ch >= '0' && ch <= '9') //as long as we get a digit
{
num = num * 10 + ch - '0'; //convert char digit to integer
ch = getchar();
}
printf("Number is %d\n",num);
}
This program only finds positive integers. I want the program to find negative integers aswell or floating point number. How do i make the program to do that? I tried using if statement inside the while loop that looks for a digit but that didnt work for me.
It appears as though fscanf will be a better solution
E.g
#include <stdio.h>
#include <ctype.h>
int main(void) {
//input format ([^0-9]*-)?[0-9]+
int ch, sign = 1;
while(!isdigit(ch=getchar())){
if(ch=='-'){
ch=getchar();//one character look-ahead
if(isdigit(ch)){
sign = -1;
}
ungetc(ch, stdin);//push back
}
}
int num;
for(num=0;isdigit(ch);ch = getchar()){
num = num * 10 + ch - '0';
}
num *= sign;
printf("Number is %d\n",num);
return 0;
}
Related
i want to use the same inputed message for the second part of the code but i can't. the first part is to count the number of alphabets and digits and the second part is to replace lower case by upper case characters. help me please!!
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MESSAGE 100
int main()
{
char message[MESSAGE];
int alphabet, digit, i;
alphabet = digit = i = 0;
printf("Please enter your message:\n");
fgets(message, sizeof message, stdin);
while (message[i] != '\0')
{
if ((message[i] >= 'a' && message[i] <= 'z')
|| (message[i] >= 'A' && message[i] <= 'Z'))
{
alphabet++;
}
else if (message[i] >= '0' && message[i] <= '9')
{
digit++;
}
else
{
i++;
}
printf("Number of Alphabets in the string is : %d\n", alphabet);
printf("Number of Digits in the string is : %d\n", digit);
scanf("%i", message);
int count, ch, i;
for (i = 0; (message[i] = getchar()) != '\n'; i++)
{
;
}
message[i] = '\0';
count = i;
printf("The given message is:%s\n", message);
printf("Case changed message is:\n");
for (i = 0; i < count; i++)
{
ch = islower(message[i]) ? toupper(message[i]) : tolower(message[i]);
putchar(ch);
}
return 0;
}
}
The following proposed code:
cleanly compiles
performs the desired operation(s)
produces the expected output
follows the axiom: only one statement per line and (at most) one variable declaration per statement.
minimizes the scope of the variable i
since the numbers can never be less than 0, uses size_t rather than int in the variable definitions
properly checks for I/O errors and when an error occurs, passes the error message and the text reason the system thinks the error occurred to stderr
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MESSAGE 100
int main( void )
{
char message[MESSAGE];
size_t alphabet = 0;
size_t digit = 0;
printf("Please enter your message:\n");
if( ! fgets(message, sizeof message, stdin) )
{
perror( "fgets failed:" );
exit( EXIT_FAILURE );
}
printf( "The given message is:%s\n", message );
for( size_t i = 0; message[i]; i++ )
{
if ( isalpha( message[i] ) )
{
alphabet++;
message[i] = (islower(message[i]) ) ? (char)toupper(message[i]) : (char)tolower(message[i]);
}
else if ( isdigit( message[i] ))
{
digit++;
}
}
printf("Number of Alphabets in the string is : %zu\n", alphabet);
printf("Number of Digits in the string is : %zu\n", digit);
printf("Case changed message is: %s\n", message );
}
Just coded again:
#include <stdio.h>
#include <ctype.h>
#define MESSAGE 100
int main(void) {
char msg[MESSAGE];
int alphabet = 0;
int digit = 0;
printf("Enter a message: ");
fgets(msg, sizeof msg, stdin); // accepting the text
for (int i = 0; msg[i]; i++) { // msg[i] says -> msg[i] != '\0'
if (isalpha(msg[i])) alphabet++; // counting if alphabet occurs
if (isdigit(msg[i])) digit++; // counting if a digit occurs
}
for (int i = 0; msg[i]; i++)
msg[i] = (isupper(msg[i])) ? tolower(msg[i]) : toupper(msg[i]);
// converting from upper to lower and vice versa
// printing the details of the given text
printf("There are %d letters and %d digits in the message.\n", alphabet, digit);
// printing the converted text
printf("The converted text is: %s\n", msg);
return 0;
}
In the aforementioned code, the program will ask to get an input from the user and count both alphabet and digit wherever they're occurred and notice that here we've used isdigit() just to count if the letter given was a digit until the null-terminator occurs in the first For loop.
In the second loop, we've just converted each of the letter from upper to lower and vice versa and assigned them again into the same variable and printed them when the loop is exited successfully.
Also, notice that the punctuation marks ain't the member of either alphabet letters or digit, so they're not counted anywhere.
As a sample output:
Enter a message: Hello world, how are you 1234 doing?
There are 24 letters and 4 digits in the message.
The converted text is: hELLO WORLD, HOW ARE YOU 1234 DOING?
Do you have a clear question?
For the second part an easy trick is to look at an ASCII table and notice that 'A' is decimal 65 and 'a' is decimal 97. There is a difference of 32 between these so you can do a bitwise operation on all letters to convert to uppercase without converting the uppercase letters to lower.
This will mess up your numbers though, so you need to make sure you don't run this on those.
If you want to convert the same message then you don't need to input that again inside the while loop. Also, you have to increment 'i' for every case, if the current character is alphabet or digit, so don't put it in the else part.
Try the following implementation:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MESSAGE 100
int main()
{
char message[MESSAGE];
int alphabet, digit, i;
alphabet = digit = i = 0;
printf("Please enter your message:\n");
fgets(message, sizeof message, stdin);
while (message[i] != '\0')
{
if ((message[i] >= 'a' && message[i] <= 'z')
|| (message[i] >= 'A' && message[i] <= 'Z'))
{
alphabet++;
}
else if (message[i] >= '0' && message[i] <= '9')
{
digit++;
}
i++;
}
printf("Number of Alphabets in the string is : %d\n", alphabet);
printf("Number of Digits in the string is : %d\n", digit);
scanf("%s", message);
int count, ch;
message[i] = '\0';
count = i;
printf("The given message is:%s\n", message);
printf("Case changed message is:\n");
for (i = 0; i < count; i++)
{
ch = islower(message[i]) ? toupper(message[i]) : tolower(message[i]);
putchar(ch);
}
return 0;
}
"Don't tell me there's not one bit of difference between uppercase and lowercase letters, because that's exactly the difference."
In ASCII, you can toggle case by toggling the 6th least-significant bit.
'A' == 0x41 <-> 0x61 == 'a'
'B' == 0x42 <-> 0x62 == 'b'
'C' == 0x43 <-> 0x63 == 'c'
...
'Z' == 0x5A <-> 0x7A == 'z'
That provides an easy of changing the case, and we can do it all in one pass.
if (
( message[i] >= 'A' && message[i] <= 'Z' )
|| ( message[i] >= 'a' && message[i] <= 'z' )
) {
++letters;
message[i] ^= 0x20;
}
else if ( message[i] >= '0' && message[i] <= '9' ) {
++digits;
}
This, like your original program, makes the following assumptions:
The program will be compiled on an ASCII-based machine.
The program will be compiled for an ASCII-based machine.
You are only interested in the letters and digits in the ASCII character set.
I want to accept the string and the float value in between the '#' is present. I have tried some what like this but it's not working; it is taking the whole input as the string.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10000];
float number;
scanf("%s#%f",str,&number); //input BMW#23.5 Expected output BMW 23.5
printf("%s %f\n",str,number); //actual output BMW#23.5 0.000000
}
Can anyone help me to solve this?
Get all as a char[] and parse it:
int main()
{
char str[10000];
float number;
scanf("%s", str);
char *at_pos = strrchr(str, '#');
if (at_pos)
{
number = atof(at_pos + 1);
// manage errors in number
printf("%s %f\n", str, number);
}
else
{
// manage error
}
}
//using the "[^#]" can really save your time.
//But you can do a lot in this approach of mine. Not just in that case.
//Feel free to ignore this but if you want to check and understand the logic there, there's the code that i wrote. Then you can just improve it. Tnx.
#include <stdio.h>
int main(void)
{
char str[10000];
char c;//The idea is, collect the input 1 by 1.
float f;
float power = 10;
int counter = 0;//We need this for the string.
c = getchar();//get the first character
str[counter] = c;//store it in the first element
counter++;
c = getchar();//Since we know that the input is string, we assume that there's a next character of course.
while(c != '#')
{
//But what if the user didn't enter a '#' character?
//Do this!
if(c == 10)
{
printf("I can't find the '#' there. =)\n\n");
return 0;
}
str[counter++] = c; //Test the recently collected character if
c = getchar(); //it's '#' or not. If not, then store it
} //in the string and continue to collect the
//next characters then store each of it in
//the string again and again until it reaches the '#'. From there you stop.
//after collecting all the characters, start collecting the numbers.
c = getchar();//collect
f = c - '0';//convert character to digit. I would bet you know this. Then store it in your float variable.
c = getchar();//collect again
//then test the recently collected again. Just like before
while(c != 10 && c != '.')//10 is the ASCII of the <enter> or new line right?. //We will also stop if we encounter '.' (dot)..
{
//while if it's not 10 or dot, add it your float variable. But don't forget the rules. use the power of 10 to.
f = f * 10 + (c - '0');
c = getchar();//collect again.
}
//do this again
c = getchar();
f += (c - '0') / power;//now divide it with power
c = getchar();
power *= 10;//then increase the power.
//Now collect the decimals
while(c != 10)//just like before
{
f += (c - '0') / power; //just do this over and
power *= 10; //over again until
c = getchar(); //it reaches the ASCII 10.
}
//Test it if you got it. =)
printf("%s # %f", str, f);
return 0;
}
//here's the clean code.
#include <stdio.h>
int main(void)
{
char str[1000];
char c;
float f;
float power = 10;
int counter = 0;
c = getchar();
str[counter] = c;
counter++;
c = getchar();
while(c != '#')
{
//But what if the user didn't enter a '#' character?
//Do this!
if(c == 10)
{
printf("I can't find the '#' there. =)\n\n");
return 0;
}
str[counter++] = c;
c = getchar();
}
c = getchar();
f = c - '0';
c = getchar();
while(c != 10 && c != '.')
{
f = f * 10 + (c - '0');
c = getchar();
}
c = getchar();
f += (c - '0') / power;
c = getchar();
power *= 10;
while(c != 10)
{
f += (c - '0') / power;
power *= 10;
c = getchar();
}
printf("%s # %f", str, f);
return 0;
}
My problem is not related to scanf();
For example: input -> 542-4Output -> 5,4,2,-4
I mean, print until negative number with negative number. It's okey until negative number, but I want to print negative number too. How can I do ? Please help me. I used getchar(), isdigit(), int a=x-'0'
char x =getchar();
while(isdigit(x)){
int a=x-'0';
printf("%d,",a);
x=getchar();
}
isdigit(x) will not be true for '-', so you need to test for that separately.
Since you want to stop after the first negative number, you need to set a flag when you read the -, so you don't keep reading other negative numbers.
int neg = 0;
char x = getchar();
while (isdigit(x) || x == '-') {
if (x == '-') {
neg = 1;
} else {
int a = x - '0';
if (neg) {
a = -a;
}
printf("%d", a);
if (neg) {
break;
}
x = getchar();
}
getchar() reads a single character at a time. You will get '5', '4', '2', and '-'.
isdigit(x) doesn't work for the '-', so the loop terminates there.
What about this:
#include <stdio.h>
int main(int argc, char *argv[])
{
char x = getchar();
int a;
while (x != '\n')
{
if (isdigit(x))
{
a = x - '0';
printf("%d,", a);
}
else
printf("%c", x);
x = getchar();
}
printf("\n");
return 0;
}
How to convert a single character like char c = '5' into an int, like I can use the c that is converted into an int to do arithmetic calculation. Above I'm trying to make a simple program that you read from your keyboard a string like '123+443' and it's display the calculation between these 2 number 123+443 that is equal to 566.
#include <stdio.h>
#include <string.h>
char str[255];
int nr1 = 0;
int nr2 = 0;
int aux,i,j;
char semn;
int result;
int main(void)
{
printf("insert your calculation \n");
scanf("%s", str);
for (i=0;i<strlen(str);i++)
{
if( (str[i]== '-') || (str[i]== '+') || (str[i]== '/') || (str[i]== '*') )
{
semn = str[i];
break;
}
else
{
aux = atoi(&str[i]);
printf("convertirea nr1 = %d\n",aux);
nr1 = nr1*10 + aux;
printf("nr1 = %d\t ",nr1);
}
}
j=i;
for(i=j+1;i<strlen(str);i++)
{
aux = atoi(&str[i]);
printf("convertirea nr2 = %d\n",aux);
nr2 = nr2*aux;
printf("nr2 = %d\t",nr2);
}
printf("\n--------------\n");
printf("%d\n", nr1);
printf("%d\n", nr2);
printf("%c\n",semn);
if(semn =='-') result = nr1 - nr2;
if(semn =='+') result = nr1 + nr2;
if(semn =='/') result = nr1 / nr2;
if(semn =='*') result = nr1 * nr2;
printf("%d\n",result);
}
atoi would not work, because it expects a null-terminated string. When you pass &str[i] to it, the function proceeds to parse the rest of the string. Only for the last digit in the string will it give you the answer that you expect.
To convert a character that represents a digit to the corresponding number, subtract '0' from it:
char c = '5';
int n = c - '0'; // n == 5
The reason this works is that the ASCII (and even EBCDIC) codes that represent digits occupy a consecutive range of numbers, with the code of digit zero '0' at its beginning and '9' at the end.
everyone!
I hope someone can help me figure out something in C language.
This is my first seriously homework in IT, I have no experience and I'm learning in e-studies, so teacher help isn't very available.
I need to develop console application in C language. User need to input 10 integer numbers, if insert number isn't integer, need to output error and again re-enter new number until all 10 integer numbers will be inserted.
Everything works in case if I say that these 10 numbers can't be 0 (I make this to be sure that my if-else statement working), but won't work when I want that every input number will be check if it is integer or not.
How can I do it right.
Please help
so far my code look like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
float f;
int numbers[10];
for (i = 0; i < 10; i++)
{
scanf ("%d", &numbers[i]);
if (numbers[i] != 0)
{
scanf ("*%d", &numbers[i]);
}
else
{
printf ("\nError!Entered number is't integer \n");
printf ("\nPlease insert number again \n");
scanf("%*d", &numbers[i]);
}
}
}
#include <stdio.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
val = scanf("%d", numbers + i); // read the integer into a[i]
if(val != 1) {
while((ch = getchar()) != '\n') // discard the invalid input
; // the null statement
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
val = scanf("%d", numbers + i);
continue;
}
++i;
}
// process the numbers array
return 0;
}
I write this line again
val = scanf("%d", numbers + i);
Now it works how I need. Great - thanks a lot
There are several techniques you might use:
Read the number as a string and reject if it contains characters not suitable for an integer. The use sscanf() to convert the string to integer.
Read the number as a float and reject if it is out of integer range or it has a non-integer value.
Read the input character by character and build up an integer value. If invalid characters appear, reject the value.
scanf returns the number of input items successfully matched and assigned. You can check this value for 1 for each call of scanf. If the value is 0, then you should discard the input to clear the stdin buffer and read input again.
#include <stdio.h>
#include <ctype.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
// read an integer and the first non-numeric character
val = scanf("%d%c", numbers + i, &ch);
// if the number of items assigned by scanf is not 2 or if
// the first non-numeric character is not a whitespace, then
// discard the input and call read input again.
// for example input of type 32ws are completely discarded
if(val != 2 || !isspace(ch)) {
while((ch = getchar()) != '\n') // discard the invalid input
; // the null statement
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
++i;
}
// process the numbers array
return 0;
}
Although I am not entirely clear on the details of your question, here is an outline of code similar to what you want:
int main(void)
{
int i;
int numbers[10];
int sum = 0;
for(i=0; i<10; ++i)
{
printf("Enter #%d:\n", i+1);
scanf("%d", numbers+i);
if (numbers[i] % 2 == 0) // Then Number is even
{
sum += numbers[i];
}
}
printf("The sum of only the even numbers is %d\n", sum);
getch();
return 0;
}
To read an int, suggest fgets() then sscanf() or strtol()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i;
int numbers[10];
for (i = 0; i < 10; ) {
char buffer[50];
if (fgets(buffer, sizeof buffer, stdin) == NULL) break;
int n; // number of `char` parsed
if (sscanf(buffer, "%d %n", &numbers[i], &n) != 1 || buffer[n] != '\0') {
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
i++;
}
return 0;
}
The strtol() approach. This detects overflow issues:
if (fgets(buffer, sizeof buffer, stdin) == NULL) break;
char *endptr;
errno = 0;
long num = strtol(buffer, &endptr, 10);
if (errno || num < INT_MIN || num > INT_MAX) Handle_RangeError();
if (buffer == endptr || *endptr != '\n') Handle_SyntaxError();
numbers[i] = (int) num;
Recommend making a int GetInt(const char *prompt) function that can be used repeatedly.
User input is evil. Do not trust it until well vetted.