Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In the code below, if I enter 11(1 and 1), the output is:[]1. [] part is not garbage, I just used the symbols("[]") to express the empty output. Therefore the real output is just 1 with one empty space if front of 1.
int main(void)
{
int x = 1;
char y = 1;
x = getchar();
y = getchar();
x = x - x;
putchar(x);
putchar(y);
}
In addition, if I replace x = x - x; to
x -= 3;
and enter 11 or 22, it gives me output like *1 or /2.
Why is this happening?
Thank you.
You have to think in terms of ASCII values. When you perform x = x - x, you're saying x = 0 (the ascii code for whatever character I type in for x minus itself is always 0)
Then look up 0 in the ASCII table, and you'll see null. So it will print null (looks like a space) and a 1.
When you perform x -= 3;, you're taking the numeric ascii code for the character you typed in, and subtracting 3. If you look at the ASCII table, you'll notice that 3 characters before the character 1 is * and three characters before 2 is /. This explains the results you are getting.
If you intend to convert the characters into the numeric values it represents, there is a bunch of ways to do this, you can subtract '0' or use the atoi function after converting the char to a string in C.
-'0' method
int numeric = x - '0';
atoi method requires a conversion to string.
char str[2] = "\0";
str[0] = x;
int numeric = atoi(str);
Both these will not make sense if you typed in a non-numeric character, e.g. aa
Related
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 2 years ago.
Improve this question
I want to create a function to take a string like this "2014-02-13T06:20:00"
and to convert to a long long int like 20140213062000.
Has anyone a idea how this can be done?
Here is an algorithm, you will just write the code:
define a long long variable n and initialize it to 0.
for each character c in the string:
if c is a digit, ie greater or equal to '0' and less or equal to '9':
multiply n by 10 and add the value represented by c, store the result in n.
else:
ignore the non digit character
n should have the expected value.
This would convert positive values. If the string has an initial - indicating a negative number, you would test that and negate the number at the end. Note also that overflowing the range of long long int has undefined behavior with this approach.
Your attempt in the comment needs some improvements:
long long string_To_long(const char sl[]) {
long long int n = 0;
for (int i = 0; sl[i] != '\0'; i++) {
char c = sl[i];
if (c >= '0' && c <= '9')
n = n * 10 + (c - '0');
}
return n;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have no problem in generate random numbers with rand()
I have to create an output file with a string of char e.g. "AQSDJEIOFHDUK"
When the result of rand ()%26 +1 is 1 I've to print in the file "A" when the result is "2" B and so on. I already know a priori how many char will be in the string let's say 50.
I've to do that in C language.
Which function I should use?
Strcat?
Simple set an array with random letters selected via rand()
#define RANDOM_STRING_LENGTH 50
char buf[RANDOM_STRING_LENGTH + 1];
for (size_t i = 0; i < RANDOM_STRING_LENGTH; i++) {
buf[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand() %26];
}
buf[RANDOM_STRING_LENGTH] = '\0';
puts(buf);
You can use the ASCII table of characters to generate valid characters. The base for the uppercase alphabet is at 65, so when you generate
int rnd = rand() % 26;
you can say something like
char new_char = 65 + rnd;
or as others have stated, it is easier to read
char new_char = 'A' + rnd;
which should give you one character in the ascii table of characters based off of the result of rand() % 26. Remember, in C an unsigned char is really just a data type that can range from the number 0, to the number 255.
(as stated below, a signed char can range from -126 to 127)
Things like 'a' and 'b' are translated into their ascii equivalent. (i.e. the corresponding number between 0 and 255 that they represent.)
(unless you are using UNICODE of course.)
I hope this helped.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm beginner in C programming (just started) and i need help from you to understand the output of this very simple code:
int main()
{
int x=1;
for (;x<=10;x++);
printf("%d\n",x);
return 0;
}
output is:
11
the same output if x value is <=11
and if x value is 12 or more, it prints the exact value of x (ex: if int x=12; the output is 12).
how did the computer understand this code?
So,
int main()
{
int x=1; // line 1
for (;x<=10;x++); // line 2
printf("%d\n",x); // line 3
return 0; // line 4
}
Line 1 initializes x to 1.
Line 2 keeps increasing x by 1 until it reaches 11. The first semicolon indicates "don't do anything before starting the loop", x<=10 indicates keep going until x > 10 (so when x = 11) and x++ means increase x by 1 each time. If x >= 11, this line gets basically skipped because x is already greater than 10.
Line 3 prints out x to the command line (in this case, x = 11 if x started out less than 11 or just x if x started at >= 11 due to the previous line)
Line 4 means the program was successful, exit the program.
for is this:
for(*init-expr*; *test-expr*; *update-expr*)
*body-statement*
Or rather, commonly, it can be decribed like this:
*init-expr*;
while(*test-expr*){
*body-statement*
*update-expr*;
}
and, your for statement is followed by a semicolon, where body-statement is.So, it is a "null statement", just loop and update x, when finishes the loop, just print the x after loop, so, the output is 11.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The program is suppose to convert binary number to decimal form. Only using scanf() and printf() library functions. Takes in a char array from user ---no prompt outputs decimal form, function must be used with parameter (char binaryString[]) after conversion result must be printed out in main. Program does not work don't think I'm converting the binary form to decimal form correctly in function binaryToDecimal since i cant use pow() I'm lost
#include <stdio.h>
#include <math.h>
int binaryToDecimal(char binaryString[]) {
int c, j = 1, decimalNumber = 0;
for (binaryString[c = 0]; binaryString[c] > binaryString[33];
binaryString[++c]) {
while (binaryString[c] != 0) {
remainder = binaryString[c] % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryString[c] = binaryString[c] / 10;
}
}
return decimalNumber;
}
int binaryToDecimalMain() {
int arraysize = 33;
char binaryString[arraysize];
scanf("%32s", binaryString);
printf("%d",binaryToDecimal(binaryString []);
return 0;
}
I not give you the algorithm because it's seems that you are learning how to program and it is important to you to learn to discover how to solve the problems that are given to you.But I can give you some hints:
use binaryString only to compare with '0' or '1'. Don't try to make any operations like '%' on it.
iterate on the binaryString character by character (no while inside for [this is only for this case, there some algorithm that is necessary to do something like this])
your logic to convert is on the right track
Also you should call your main function main.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following scenario where any input string will be converted into an integer.
Example:
result = get_integer_from_string("100");
result == 100; // true
How can I write this function without using any libraries? I am able to do it by using libraries.
Follow these Steps:
Parse the input string.
Check if the character is a digit or not.
Use some logic to convert digit in character format to integer format.
Also, you can implement Exception in case, input is not integer string.
I cannot tell you the code, it would not help you in learning, try implementing code yourself, it is very easy!!
Loop over the string, from the end to the start. Get each digit, and convert it to a decimal value. Multiply the first (in the backward loop) by 1 and store the result. Multiply the second by 10 and add to the result of the previous. And so on.
This is very prone to error conditions, but should work if string is valid integer:
int str2int(const char* str) {
int result = 0;
char* p = str;
for (;;) {
char c = *p++;
if (c < '0' || c > '9')
break;
result *= 10;
result += c - '0';
}
return result;
}
It has behavior close to atoi() - stop processing on any non-digit, and return 0 for empty input.