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.
Related
I am fairly new to programming and I am trying to convert a string containing a base 10 number to an integer value following this pseudo algorithm in c.
start with n = 0
read a character from the string and call it c
if the value of c is between '0' and '9' (48 and 57):
n = n * 10 +(c-'0')
read the next character from the string and repeat
else return n
here is the rough basics of what i wrote down however I am not clear on how to read a character from the string. i guess im asking if i understand the pseudocode correctly.
stoi(char *string){
int n = 0;
int i;
char c;
for (i = 0;i < n ; i++){
if (c[i] <= '9' && c[i] >= '0'){
n = n *10 +(c - '0')}
else{
return n
}
}
}
You were close, you just need to traverse the string to get the value of each digit.
Basically you have two ways to do it.
Using array notation:
int stoi(const char *str)
{
int n = 0;
for (int i = 0; str[i] != '\0'; i++)
{
char c = str[i];
if ((c >= '0') && (c <= '9'))
{
n = n * 10 + (c - '0');
}
else
{
break;
}
}
return n;
}
or using pointer arithmetic:
int stoi(const char *str)
{
int n = 0;
while (*str != '\0')
{
char c = *str;
if ((c >= '0') && (c <= '9'))
{
n = n * 10 + (c - '0');
}
else
{
break;
}
str++;
}
return n;
}
Note that in both cases we iterate until the null character '\0' (which is the one that marks the end of the string) is found.
Also, prefer const char *string over char *string when the function doesn't need to modify the string (like in this case).
Congrats on starting your C journey!
One of the most important aspects of strings in C is that, technically, there are none. A string is not a primitive type like in Java. You CAN'T do:
String myString = "Hello";
In C, each string is just an array of multiple characters. That means the word Hello is just the array of [H,e,l,l,o,\0]. Here, the \0 indicates the end of the word. This means you can easily access any character in a string by using indexes (like in a normal array):
char *myString = "Hello";
printf("%c", myString[0]); //Here %c indicates to print a character
This will then print H, since H is the first character in the string. I hope you can see how you can access the any character in the string.
I'm having trouble in converting numbers to float using getchar() method to solve my problem. For my problem I need to store characters in an array of fixed size = 50. Also, storing in an array only happens when there is a space ' ' or a newline \n read using getchar(). This happens until EOF is read. At last, the float number and it's double (with a tab space) is returned and printed using printf.
As per instructions, only getchar() is allowed. Functions like scanf(), fgets(), atoi(), atol(), atof(), strtol(), strtoul() or an extra array can not be used.
Here is what I've come up with till now. ( see sample input and output at bottom )
#include <stdio.h>
#define SIZE 50 // assume no more than 50 literals in input
int main(){
float c;
float u;
float value = 0.0;
float resu[SIZE];
int index = 0;
int i;
char sub = '0';
value = 0;
c = getchar();
while ( c != EOF){
if(c == '.'){
u = 0.1;
}
else if (c == ' ' || c == '\n'){
if(u == 0.1){
value = value * 0.1;
}
resu[index] = value;
index++;
value = 0;
}
if( c >= '0' && c <= '9'){
value = value * 10 + (c-sub);
}
c = getchar(); // read next
}
//printing the result
for(i=0; i < index; i++)
printf("%.4lf \t %.4lf\n", resu[i],resu[i] *2.0);
return 0;
}
(Note- There is a tab between the original number and it's double)
Sample Input:
2.3 4.56
43.3 43 5.3
.3 1.2
Sample Output:
2.3000 4.6000
45.6000 91.2000 //ERROR
43.3000 86.6000
4.3000 8.6000 //ERROR
5.3000 10.6000
0.3000 0.6000
1.2000 2.4000
Two things you don't do is initialize u or reset u for each word.
float u = 0;
....
else if (c == ' ' || c == '\n') {
if (u == 0.1){
value = value * 0.1;
}
resu[index] = value;
index++;
value = 0;
u = 0; // Reset it for next number
}
Also, you hard-code u = 0.1, but that only works when there is only 1 decimal place. That may be ok for this assignment, but a better option would be to count the digits after the decimal.
#include <stdbool.h>
#include <math.h>
#include <ctype.h>
...
int digits_after_decimal = 0;
bool have_decimal_point = false;
int value = 0;
int c;
while ((c = getchar()) != EOF) {
// Decimal point found?
if ('.' == c) {
have_decimal_point = true;
}
else if (isdigit(c)) {
// Add this digit to integer value
// Parentheses not required but added for clarity
value = (value * 10) + (c - '0');
// If decimal point already found, increment count
if (have_decimal_point) digits_after_decimal += 1;
}
// Complete word. Save and reset
// TODO: Multiple spaces between words?
else if (' ' == c || '\n' == c) {
// Divide by the correct power of 10 based on
// the number of digits after the decimal point
resu[index++] = value / pow(10, digits_after_decimal);
if (index == SIZE) break; // Avoid overflow
// Reset for next number
digits_after_decimal = 0;
have_decimal_point = false;
value = 0;
}
// TODO: Negative numbers?
}
I have an unsigned char array unsigned char* name = malloc(nameLength); - how can I print it with printf? %sdoes not seem to work correctly, neither does %u (seeing random icons).
Here's how I create the data I want to print:
__int32 nameLength;
ReadProcessMemory(hProcess, (LPCVOID)(classNamePtr + 0x0004), &nameLength, sizeof(__int32), 0); //Reads nameLength to be 13 in this case
unsigned char* name = malloc(nameLength+5); //Add 5 for good measure, it is null terminated
ReadProcessMemory(hProcess, (LPCVOID)(nameStrPtr), name, nameLength, 0);
name[nameLength] = 0; //null terminate
printf("%s", name); //Outputs single character strange characters, like an up icon
When one detects a non-printable char, output an escape sequence or hexadecimal value
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int printf_ByteArray(const unsigned char *data, size_t len) {
size_t i;
int result = 0;
for (i = 0; i < len; i++) {
int y;
int ch = data[i];
static const char escapec[] = "\a\b\t\n\v\f\n\'\"\?\\";
char *p = strchr(escapec, ch);
if (p && ch) {
static const char escapev[] = "abtnvfn\'\"\?\\";
y = printf("\\%c", escapev[p - escapec]);
} else if (isprint(ch)) {
y = printf("%c", ch);
} else {
// If at end of array, assume _next_ potential character is a '0'.
int nch = i >= (len - 1) ? '0' : data[i + 1];
if (ch < 8 && (nch < '0' || nch > '7')) {
y = printf("\\%o", ch);
} else if (!isxdigit(nch)) {
y = printf("\\x%X", ch);
} else {
y = printf("\\o%03o", ch);
}
}
if (y == EOF)
return EOF;
result += y;
}
return result;
}
If data contained one of each byte, sample follows:
\0...\6\a\b\t\n\v\f\xD\xE\xF\x10...\x1F !\"#$%&\'()*+,-./0123456789:;<=>\?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F...\xFE\o377
The selection of escape sequences will vary with code goals. The set above attempts to conform to something a C parser would accept.
Note: With the last else, always outputting a 3-digit octal sequence has scanning advantages, but folks are more accustomed to hexadecimal than octal.
Adjusted to conditionally print in hex depending on the following character.
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;
}
I am trying to write a program that adds, subtracts, multiplies, and divides a string of characters. Where I'm at now with the program is figuring out how to split the input string into two strings, and then perform the appropriate +-/*.
The input should look like this abc+aaa
and the output for that should be abc + aaa = bcd
How do I convert character strings into integer strings?
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
printf("This is a pseudo arithmetic program");
char input[10];
input[10] = '\0';
char first [9];
first[9] = '\0';
char last [9];
last[9] = '\0';
int i = 0;
int b;
int e;
while (input[0] != '0') {
if (input[0] == 0){
return -1;
}
printf("\nEnter a math problem in SOS format using only lowercase letters up to 9 characters");
printf("\nEx: abc+abc... type '0' to quit \n");
scanf("%s", input);
int x = 0;
x = strlen(input);
if (strchr(input, '+')){
for (i = 0; i <= x; i++) {
if (i == '+')
strncpy(first, &input[0], i-1);
i = 0;
}
for (i = x; i >= input[0]; i--) {
if (i == '+')
strncpy(last, &input[i], x);
i = 0;
}
printf("%s", first);
printf(" + ");
printf("%s", last);
printf(" = %d", first + last);
}
There seems to be multiple problems with your code:
There is a array out of bounds happening for almost all the arrays:
char input[10];
input[10] = '\0';
In this if you want to initialize the last character with '\0' then it should be
input [9] = '\0'
Arrays indexes always start from 0.
It is not clear what is the use of below lines:
while (input[0] != '0') { if (input[0] == 0){ return -1; }
When taking input for a string, why are prompting users to enter a 0 to end it?
strrchr returns the pointer from where the searched character begins. So, you can that itself to determine where the '+' symbol is and two split the strings instead of your while loop. See strrchr man page
Also, your idea of adding characters is not clear. From your example, it appears you are considering a = 1, b = 2 etc. In such a case, if your code is case insensitive, then you can convert all your input to upper case and then do (input[0] - 'A')+1 to convert your letters like a, b, c to 1, 2, 3 etc.
Hope these pointers help. Suggest you check your problem statement again and refactor your code accordingly.