Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to multiply the numbers in a given string which has one or more spaces.
Example:
If i input 52 26 23
the output should be 31096.
I've written this code but its not working:
#include <stdio.h>
int main()
{
char input[30];
int i, num = 0, v = 1;
gets(input);
for (i = 0; input[i] != '\0'; i++)
{
if(input[i] == 32)
{
v = v * num;
if(input[i+1] != 32)
{
num = 0;
continue;
}
}
num = (num * 10) + (input[i] - 48);
}
printf("%d",v);
return 0;
}
Try this one
#include <stdio.h>
#include <string.h>
int main()
{
char str[30];
char *token;
long int mul = 1;
gets(str);
token = strtok(str, " ");
while (token != NULL)
{
mul = mul * atoi(token);
token = strtok(NULL, " ");
}
printf("%ld",mul);
return 0;
}
The problem lies in your nested if statement. Once it enters the first if statement, that means input[i]==32, therefore it can never enter the next if statement where input[i]!=32.
I also have some suggestions for improving readability. Instead of using numbers to represent the characters, use the character literals themselves!
Another thing, you only have space for 30 characters in your input buffer. If a user attempts to enter more than this, you will have a buffer overflow.
Lastly, if the user puts more than one space between numbers, the output will become 0. That may be something you may or may not want to handle.
Edit: Before, the call to gets was only grabbing characters up to the first whitespace character. I've fixed this issue with a format string in a call to scanf instead. Buffer overflow problem still applies. Also, it was not multiplying with the last parsed integer, so I added code for that after the loop. Another note, this will only work for non-negative integers, if that's something you weren't aware of initially. The code just assumes the input is nice.
Edit 2: support for input with any number of spaces before, between, or after inputs.
#include <stdio.h>
int main() {
char input[30];
int i, num = 0, v = 1;
scanf("%[^\n]s", input);
// skip leading spaces
for(i = 0; input[i] == ' '; i++);
// parse remaining input
while(input[i] != '\0') {
if(input[i] == ' ') {
v *= num;
num = 0;
// skip subsequent spaces
while(input[++i] == ' ');
continue;
}
num *= 10;
num += input[i] - '0';
i++;
}
// ignore trailing spaces
if(input[i - 1] != ' ') {
// get last parsed integer
v *= num;
}
printf("%i\n", v);
return 0;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new in C.
I've been asked to write a function that checks if the string has increasing/decreasing sequence of letters based on ASCII values + not includes white spaces(tabs,new lines etc.).
For example: demo is a very increasing string
beef is an increasing string
aa or zzz is an increasing string
tonic is a very decreasing string
spoon is a decreasing string
suddenly has no clear sequence.
So I wrote this code,it works but not so well..can you help me to improve it a little bit?
#include <stdio.h>
void f_sequence (char str[]);
int main()
{
char strl[101];
printf("your string is:\n");
scanf("%s\n", strl);
f_sequence(strl);
return 0;
}
void f_sequence(char str[])
{
int increase=0;
int decrease=0;
int match=0;
int i = 1;
if(!str[0])
printf("empty");
else if(!str[1])
printf("need more chars");
for(i=1; str[i]; i++)
{
if (str[i] == str[i-1])
match = 1;
if (str[i] > str[i-1])
increase = 1;
if (str[i] < str[i-1])
decrease = 1;
}
if((decrease==1) && (increase==0) && (match==0))
printf("we have a very descreasing sequence in here");
if((decrease==0) && (increase==1) && (match==0))
printf("we have a very increasing sequence in here");
if((decrease==1) && (increase==0) && (match==1))
printf("we have a descreasing sequence in here");
if((decrease==0) && (increase==1) && (match==1))
printf("we have an increasing sequence in here");
if((decrease==0) && (increase==0) && (match==1))
printf("we have an increasing sequence in here");
if((decrease==1) && (increase==1))
printf("not increasing and not decreasing");
puts("");
}
To ignore whitespaces, you can use isspace from <ctype.h> and skip in your calculations:
for(i = 1; str[i]; i++)
{
if (isspace((unsigned char)str[i])) continue;
...
}
But as is, you can't read input string with whitespaces as scanf with %s would stop reading at the first whitespace. You need fgets to read a line (so that you could read a string with whitespaces):
int main()
{
char strl[101];
printf("your string is:\n");
if (fgets(strl, sizeof strl, stdin)) {
char *p = strchr(strl, '\n');
if (p) *p = '\0'; // Remove newline if present
f_sequence(strl);
}
}
fgets would also read the newline character if there's space in the buffer which you may want to remove as shown (include <string.h> for strchr).
Use a function like below to remove whitespaces:
void removeSpaces(char *str)
{
// To keep track of non-space character count
int count = 0;
// Traverse the given string. If current character
// is not space, then place it at index 'count++'
for (int i = 0; str[i]; i++)
if (str[i] != ' ')
str[count++] = str[i]; // here count is
// incremented
str[count] = '\0';
}
And then add this function in the first line of f_sequence function. like this:
removeSpaces(str);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wrote this program to find the total number of digits from a line of text entered by user. I am having error on using getchar(). I can't seem to figure out what am I doing wrong?
#include <stdio.h>
#define MAX_SIZE 100
void main() {
char c[MAX_SIZE];
int digit, sum, i;
digit, i = 0;
printf("Enter a line of characters>");
c = getchar();
while (c[i] != '\n') {
digit = 0;
if (c [i] >= '0' && c[i] <= '9') {
digit++;
}
}
printf("%d\n", digit);
}
I will be adding all the digits I found using sum variable. but I am getting error on getchar() line. HELP??
You can enter a "line of text" without using an array.
#include <stdio.h>
#include <ctype.h>
int main(void) { // notice this signature
int c, digits = 0, sum = 0;
while((c = getchar()) != '\n' && c != EOF) {
if(isdigit(c)) {
digits++;
sum += c - '0';
}
}
printf("%d digits with sum %d\n", digits, sum);
return 0;
}
Note that c is of type int. Most of the library's character functions do not use char type.
Edit: added the sum of the digits.
Weather Vane's answer is the best and simplest answer. However, for future reference, if you want to iterate (loop through) an array, it would be easier to use a for loop. Also, your main function should return an int and should look like this: int main(). You will need to put a return 0; at the end of your main function. Here is a modified version of your program that uses a for loop to loop through the character array. I used the gets function to read a line of characters from the console. It does wait for the user to enter the string.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char c[MAX_SIZE];
int digit = 0;
printf("Enter a line of characters>");
gets(c);
for (int i = 0; i < MAX_SIZE; i++)
{
if (c[i] == '\n') break; // this line checks to see if we have reached the end of the line. If so, exit the for loop (thats what the "break" statment does.)
//if (isdigit(c[i])) // uncomment this line and comment or delete the one below to use a much easier method to check if a character is a digit.
if (c [i]>= '0' && c[i] <= '9')
{
digit++;
}
}
printf("%d\n", digit);
return 0;
}
An easy of getting the number of digits in an integer is the use of log10() function which is defined in math.h header. Consider this program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, const char *argv[]) {
system("clear");
unsigned int i, sum = 0, numberOfDigits;
puts("Enter a number");
scanf("%u", &i);
numberOfDigits = (int) (log10(x) + 1);
system("clear");
while(i != 0) {
sum += (i % 10);
i /= 10;
}
fprintf(stdout, "The sum is %i\n", sum);
fflush(stdin);
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need to convert a string in the a ± bi form to an int Real and an int Im. And in the case that the string isn't in that form, print an error. I have an idea to convert the a to the int and also the b but I don't know what to do with de imaginary number if it is positive.
i.e.
0,034 - 1,2i
>a=0,034
>b=-1,2
0,25
>Error, you must write in "a±bi" form
3,234 + 34,43i
>a=3,234
>b=34,43
ps: I found this link but it is in C++ and I don't know what it is doing
EDIT: THE REAL NUMBER COULD HAVE A PLUS OR MINUS.
It is quite simple, the C-standard has all you need:
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 100
// ALL CHECKS OMMITTED!
int main()
{
double a, b;
char buffer[BUFFER_SIZE];
int count = 0;
char c;
char *endptr;
while ((c = fgetc(stdin)) != EOF) {
if (c == '\n') {
// make a proper C-string out of it
buffer[count] = '\0';
// reset counter for the next number
count = 0;
// strtod() is intelligent enough to
// stop at the end of the number
a = strtod(buffer, &endptr);
// endptr points to the end of the number
// skip whitespace ("space" only)
while (*endptr == ' ') {
endptr++;
}
// skip the +/- in the middle
endptr++;
// strtod() skips leading space automatically
b = strtod(endptr, NULL);
printf("a = %g, b = %g\n", a, b);
}
// read all into a big buffer
buffer[count++] = (char) c;
if (count >= BUFFER_SIZE) {
fprintf(stderr, "Usage: type in complex numbers in the form \"a + b\"\n");
exit(EXIT_FAILURE);
}
}
exit(EXIT_SUCCESS);
}
See? No need to worry.
Use sscanf():
"%lf" scan 0 or more white spaces and then scan a double
" " scan 0 or more white spaces
"%1[+-]" scan a non-empty string made up of + or - and only up to 1 character in length.
"i" scan for an i character
"%n" store the count of characters scanned so far. (does not add to the return count.)
#include <complex.h>
#include <stdio.h>
double complex ALconvert(const char *s) {
int n = 0;
double re, im;
char sign[2];
if (sscanf(s, "%lf %1[+-] %lf i %n", &re, sign, &im, &n) != 3 || s[n]) {
puts("Error, you must write in \"a+/-bi\" form");
return 0.0/0.0; // TBD_ErrorCode;
}
if (sign[0] == '-') {
im = -im;
}
return re + im*_Complex_I;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to write a program that converts an user input (which is a string) to an Integer. In the same time it should check, if the user input really is a number.
And also everything in one method.
and NO LIBRARY FUNCTIONS allowed.
I can't figure any idea how to do it. All I got for the beginning is just this pathetic structure
#include <stdio.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%c, &input");
for (i = 0; i < 100; i++)
{
}
}
I appreciate any help, thanks
The conversion is the easy part...
But if you must not use library functions,
there is only one way to take a string, and that is argv;
there is only one way to give an integer, and that is the exit code of the program.
So, without much ado:
int main( int argc, char * argv[] )
{
int rc = 0;
if ( argc == 2 ) // one, and only one parameter given
{
unsigned i = 0;
// C guarantees that '0'-'9' have consecutive values
while ( argv[1][i] >= '0' && argv[1][i] <= '9' )
{
rc *= 10;
rc += argv[1][i] - '0';
++i;
}
}
return rc;
}
I did not implement checking for '+' or '-', and did not come up with a way to signal "input is not a number". I also just stop parsing at the first non-digit. All this could probably be improved upon, but this should give you an idea of how to work around the "no library functions" restriction.
(Since this sounds like a homework, you should have to write some code of your own. I already gave you three big spoons of helping regarding argv, the '0'-'9', and the conversion itself.)
Call as:
<program name> <value>
(E.g. ./myprogram 28)
Check return code with (for Linux shell):
echo $?
On Windows it's something about echo %ERRORLEVEL% or somesuch... perhaps a helpful Windows user will drop a comment about this.
Source for the "'0'-'9' consecutive" claim: ISO/IEC 9899:1999 5.2.1 Character sets, paragraph 3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
I'm sure this is preserved in C11, but I only have the older C99 paper available.
Take hightes digit and add it to number, multiply the number by 10 and add the next digit. And so on:
#include <stdio.h> // scanf, printf
void main()
{
char input[100];
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
int number = 0;
int neg = input[0] == '-';
int i = neg ? 1 : 0;
while ( input[i] >= '0' && input[i] <= '9' )
{
number *= 10; // multiply number by 10
number += input[i] - '0'; // convet ASCII '0'..'9' to digit 0..9 and add it to number
i ++; // step one digit forward
}
if ( neg )
number *= -1;
printf( "string %s -> number %d", input, number );
}
input[i] - '0' works, because ASCII characters '0'..'9' have ascending ASCII codes from 48 to 57.
So basically you want to know how something like the standard library atoi works. In order to do this, you need to consider how strings represent numbers.
Basically, a string (that represents a number) is a list o digits from 0 to 9. The string abcd (where a, b, c, d are placeholders for any digit) represents the number a*10 ^ 3 + b*10^2 + c * 10 + d (considering base 10 here, similar for other bases). So basically you need to decompose the string as shown above and perform the required arhitmetic operations:
// s - the string to convert
int result = 0;
for (int index = 0; index < strlen(s); index++) {
result = result * 10 + s[index] - '0';
}
The operation s[index] - '0' converts the character that represent a digit to its value.
// the function returns true for success , and false for failure
// the result is stored in result parameter
// nb: overflow not handled
int charToInt(char *buff,int *result){
*result=0;
char c;
while(c=*buff++){
if((c < '0') || (c >'9')) // accept only digits;
return 0;
*result *= 10;
*result += c-'0';
}
return 1;
}
Lot of things which are missed. Firstly taking a string in is done by scanf("%s",input); By the way in which you are receiving it, it only stores a character, secondly run the loop till the length of the string recieved. Check the below code.
#include <stdio.h>
#include<string.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
for (i = 0; i < strlen(input); i++)
{
if(input[i]>=48 && input[i]<=57)
{
//do something, it is a digit
printf("%d",input[i]-48);
//48 is ascii value of 0
}
}
Try it:
#include <stdio.h>
void main()
{
char input[100];
int i,j;
int val = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s",input);
for(j=0; input[j] != '\0'; j++); // find string size
for (i = 0; i < j; i++)
{
val = val * 10 + input[i] - 48;
}
}
If you want your code to be portable to systems that don't use ASCII, you'll have to loop over your char array and compare each individual character in the source against each possible number character, like so:
int digit;
switch(arr[i]) {
case '0':
digit=0; break;
case '1':
digit=1; break;
// etc
default:
// error handling
}
Then, add the digit to your result variable (after multiplying it by 10).
If you can assume ASCII, you can replace the whole switch statement by this:
if(isdigit(arr[i])) {
digit=arr[i] - '0';
} else {
// error handling
}
This works because in the ASCII table, all digits are found in a single range, in ascending order. By subtracting the ordinal value of the zero character, you get the value of that digit. By adding the isdigit() macro, you additionally ensure that only digit characters are converted in this manner.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
The program requires a user to insert a number. Let's say we put 149. Now the program prints every number that has 0 digits in them till the number 149 (Including the number). So it's going to be 10,20,30,40,50,60,70,80,90,100,101...110..140 [Let's say the limit would be till 10000]
I have been trying to do this, but i only added +10 to every one, but that cannot be done >100 where it is 101,102..
Use the function sprintf to convert an integer to a string and then search for the character '0' in the string. If found, then print the number. Here's a simple working program implementing this idea.
#include <stdio.h>
#include <string.h>
#define MAXLEN 50 // max number of digits in the input number
int main(void) {
char buf[MAXLEN + 1]; // +1 for the null byte appended by sprintf
char ch = '0'; // char to be searched for in buf
int i, x;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
if(strchr(buf, ch)) // strchr returns a pointer to ch if found else NULL
printf("%d\n", i);
}
return 0;
}
You can also extract each digit of an integer in the given range and check it for zero. Here's a naive implementation.
#include <stdio.h>
int main(void) {
int i, x;
int r;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
for(r = i; r > 0; r /= 10) {
if(r%10 == 0) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
The simple approach would be to iterate through all natural numbers up to the target number and testing each of them to see if they have any zero digits. Note that the last digit of a non-negative integer i can be obtained as the remainder from division by the base (i % 10 here). Also remember that integer division in C truncates decimals, e.g., (12 / 10) == 1
As a start, consider to convert each number to char [] and then check whether it contains a '0' or not.
To read on:
How to check if a int var contains a specific number
Count the number of Ks between 0 and N
I think this would be the answer.
int j;
for(int i=1;i<150;i++){
j=i;
while(j>0)
{
if(j%10==0)
{
printf("%d\n",i);
break;
}
else
j=j/10;
}
}