convert a char element from an array to an int - c

Hi I'm trying to convert elements of an array into integers using input from the user.
#include <stdio.h>
#include <string.h>
int main()
{
char i[9]={'-','-','-','-','-','-','-','-','\0'};
int j;
printf ("enter an integer for an element ");
sscanf(i, "%d", &j);
return 0;
}
I read somewhere that using sscanf is one way to do it but I don't know the correct way to use it.

scanf reads from the standard input.
sscanf reads from a string.
Example of scanf usage:
#include <stdio.h>
int main()
{
char str1[20];
printf("Enter name: ");
scanf("%s", str1);
printf("First char converted to int: %d\n", str1[0]);
int j = str1[1];
printf("Second char converted to int: %d\n", j);
return(0);
}
Input and Output:
Enter name: marcel
First char converted to int: 109
Second char converted to int: 97

As Marcel said, there are two different functions that do different things.
You request convert elements of an array into integers using input from the user, so I can think you want this:
char i[9]={'-','-','-','-','-','-','-','-','\0'};
int j;
printf ("enter an integer for an element ");
scanf("%i", &j);
printf("Element[ %i ] in integer is: %i", j, i[j]);

Related

Function is telling me the length of the string and not the number of occurrences of the char inputted by the user

#include <stdio.h>
#include <string.h>
int countLetters(char *string1, char letter){
int count=0;
for(int i=0; i<strlen(string1); i++){
if(string1[i]=letter){
count++;
}
}
return count;
}
int main(){
char string1[200];
char letter;
int count;
printf("\nEnter the string: \n");
fgets(string1, 200, stdin);
printf("\nEnter character to be searched: \n");
scanf("%c", &letter);
count = countLetters(string1, letter);
printf("\nThe number of occurrences: %d", count);
}
I was expecting for the function to output the number of times each letter of the array was equal to the char(letter) inputted by the user, but it is just giving me the length of the string.
Change the line:
if(string1[i]=letter){
to
if(string1[i]==letter){
Note, that the string1[i]=letter was overwriting data in string1[i].
You have to use equal equal to operator instead of assignment operator in if condition like this
if(string1==latter)
in your if condition if(string1=latter) value of latter variable is assign to string1[i]

Why am I getting garbage value here?

Its a program to convert integer stored in a string into an int. Please help.
#include<stdio.h>
#include<math.h>
int main()
{
int num, n, i;
num = 0;
printf("Enter n\n");
scanf("%d", &n);
char string[n+1];
printf("Enter the number\n");
scanf("%s", &string);
for(i=0;string[i]!='\0';i++)
{
num = num + string[i]*pow(10,n-i-1);
}
printf("The required number is %d", num);
return 0;
}
In typical environment, character codes for digits are not equal to the numbers the digits represent for.
Character codes for digits in C are defined to be continuous, so you can convert the character codes to the corresponding numbers by subtracting '0' from the character code.
num = num + (string[i]-'0')*pow(10,n-i-1);
By the way, there are some better ways to do the conversion:
sscanf(string, "%d", &num); /* available in stdio.h */
num = atoi(string); /* stdlib.h is required for atoi() */
Also note that scanf("%s", &string); invokes undefined behavior because a pointer to array is passed where char* (a pointer to char) is required. The & should be removed.
In your code the size of your string must be equal to n+1 ,so you can removed all this
printf("Enter n\n");
scanf("%d", &n);
char string[n+1];
for(int i=strlen(string)-1;i>=0;i--)
I started from the last caracter in my string to the first caracter and I multiplied each caracter by j (j=1 then j=10 then j=100 .....)
#include<stdio.h>
#include<math.h>
int main()
{
int j=1;
char string[100];
printf("Enter the number\n");
scanf(" %s", string);
int num=0;
for(int i=strlen(string)-1;i>=0;i--)
{
int k=string[i]-'0';//subtract each case by '0'
num=num+k*j;
j=j*10;
}
printf("The required number is %d", num);
return 0;
}

Variable Use Fgets with a char array in C

I'm trying to read in a grade (1-10) into an array called moduleGrades.
The fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin); causes an error, yet what i've typed is exactly what I need. I want to store 3 grades (if the number of modules entered was 3)
many thanks.
#include<stdio.h>
#include <string.h>
char name[30];
int moduleNumber;
char moduleGrades[2];
int main(int argc, char **argv)
{ //read name & module amount
printf ("Please enter your name: ");
fgets(name, sizeof(name), stdin);
printf ("How many Modules: ");
scanf("%d", &moduleNumber);
int i;
for (i = 1; i <= moduleNumber; i++)
{
printf ("Please enter module %d grade ", i);
fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin);
}
printf("%d", moduleGrades[0]);
printf("%d", moduleGrades[1]);
printf("%d", moduleGrades[2]);
return 0;
}
If you want to print three chars, as indicated by your output, then your array must also be able to hold three chars:
char moduleGrades[2];
Also this loop here:
int i;
for (i = 1; i <= moduleNumber; i++)
This isn't wrong in itself because you subtract the 1 you're off inside the loop, but I would do this and just put this instead:
for (int i = 0; i < moduleNumber; i++)
The fgets call inside the loop is wrong. You're giving it a char instead of a pointer to char. Instead of using fgets, I would just use scanf again:
scanf(" %c", &moduleGrades[i]);
When you print those char that you read in, you need to use the %c format specifier, too:
printf("%c", moduleGrades[0]);
This way it'll print the char that you read in earlier. For instance, if you pressed A, it will print A. With %d it will probably print 65, but it's undefined behavior, so anything else than that might happen instead and there's no guarantee on what exactly will happen.

Storing Integers in an Char Array in C

Im doing some work for Uni and wrote a programm which stores Integers in an char Array and converts them to their ASCII Values and prints them at the end. My code did not work before and only started working when i changed "%c" to "%i" in my scanf line. My question: Why does it have to be "%i" when i wanna store those Numbers in an char Array and not an Int Array. Thanks!
My code:
#include <stdio.h>
int main()
{
int i; /counter
char numbers[12];
printf("Please enter 12 Numbers\n");
for(i = 0; i < 12; i++){
printf("please enter the %i. Number\n", i+1);
scanf("%i", &numbers[i]);// <-- changed "%c" to "%i" and it worked.why?
}
for(i = 0; i < 12;i++){
printf("The %i.ASCII value is %i and has the Char %c\n", i+1, numbers[i], numbers[i]);
}
return 0;
}
%c is for reading a single character. So for example if you type in "123", scanf will read '1' into the char variable and leaves the rest in the buffer.
On the other side %i is the specifier for int and will therefore lead to undefined behavior when trying to read in a char.
I think what you are looking for is the %hhi specifier, which reads a number into a char variable.

how to display entered letter in c?

I am new to c programming. I have created a program for entered letters and finally displayed the entered letters.. but it displayed only final letters always.. please help .. i know its simple question but am beginner so please help guys..
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%s\n",&z);
}
return 0;
}
Problems:
You should use %c (for character) instead of %s (for string).
Use a character array for storing multiple characters. Read about arrays here.
Remove & from printf() in the second for loop.
Try this:
int main()
{
char z[10]; //can hold 10 characters like z[0],z[1],z[2],..
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
Please look into this for more details on scanf. You have given scanf("%s",&z); %s is for reading strings(array of chars except newline char and ended with null char). So if you put this inside loop you wont get desired result. And if you want read only a char at a time use %c here c for Character.
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
char z is a place holder for one character only. And you are over writing what you set z to in the for loop. To take in more characters, use a char array as others have mentioned.
Or print the characters in the same you loop you are scanning them:
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
printf("letter scanned:%c\n", z);
}
return 0;
}
Letters are scanned using %c. And to scan multiple letters you can use char array: char z[10];
What you are trying to do can be done this way:
char z[10]; // Take some max size array
...
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]); // Scan the letters on each array position.
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]); //'printf' doesn't require address of arg as argument hence no `&` required
}
%s argument is used to scan a string of chars.
Note the difference between string of chars and array of chars. The string of chars in C needs to be terminated with ASCII Character 0 represented as \0 in char format, while the array of char is just a collection of letters which need not be terminated with \0.
The difference becomes more important when you try to perform some operation on strings such as printf, strcpy, strlen, etc.. These functions work on null character termination property of string.
For Example: strlen counts the characters in the string till it finds \0, to find out the length of string. Similarly, printf prints the string character by character until it finds the \0 character.
UPDATE:
Forgot to mention that scanf is not a good option to input char format. Use fgetc instead, with stdin as input FILE stream.
#include <stdio.h>
int main()
{
char *z;
int a;
printf("enter the no.");
scanf("%d",&a);
z = (char *) malloc(a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z);
}
return 0;
}
first error in your code is you have used "%s" instead of "%c".Second is it is impossible to store multiple values in one variable so instead of using variable use arrays.third is that you have told the user to enter the number of character that he/she wants to entered which you don't know.They can enter 1 also and 100000 also so the number of members in array is not defined.Better is to use specific number of characters in array.
finally i got the answer thank you for the help stackoverflow guys simply rocks ...
#include<stdio.h>
#include<malloc.h>
int main()
{
int a;
char *z=(char *)malloc(sizeof(a));
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z[i]);
}
printf("the entered letters are:\n");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}

Resources