How do I save integers read by getchar() to an array? - c

I am trying to make a program that will use getchar() to read three integers and store it in an array but something is wrong in my code.
#include <stdio.h>
int main( )
{
printf("Please enter three digit number 100 to 999: ");
int numEntered[2];
numEntered = getchar();
for (int i = 0; i<3; i++) {
printf("%d", numEntered[i])
}
}

Try this:
#include <stdio.h>
int main(){
printf("Please enter three digit number 100 to 999: ");
int numEntered[3];
for (int i = 0; i<3; i++){
scanf("%d", &numEntered[i]);
printf("%d", numEntered[i]);
}
return 0;
}
you need to read a value inside the for loop! Second thing, by reading with getchar(), you are getting the ascii value of the character, so.. if you read "1" and print with %d, you actually printing 49!
See the ascii table here: http://www.asciitable.com/index/asciifull.gif

let's try and and think about the problem here:
do you want to read and store an integer value? if yes -> use scanf
do you want to read a number digit by digit? if yes -> use getchar
do you want to make sure what you read has exactly 3 digits? if yes...what do you do when it does not?
if reading digit by digit, make sure you are reading numbers; getchar reads characters -> use atoi funtion or check ascii value;
Putting it all together(some assumptions were made):
int main()
{
char digits[3]; // don't use ints to store chars...
printf("enter the 3 digit number - 100 to 999: ");
for (int i=0;i<3;i++) // only the first 3 chars are read
{
char c = getchar();
if (char < '0') || (char > '9')
{
printf("invalid digit!");
exit(0);
}
digits[i] = c;
}
printf("the number entered is: %c%c%c", digits[0],digits[1],digits[2]);
}

You don't use getchar to get integer values.
Use scanf() instead.
Try this:
#include <stdio.h>
int main( )
{
printf("Please enter three digit number 100 to 999: ");
int numEntered[3];
for (int i = 0; i<3; i++){
scanf("%d",&a[i]);
printf("%d", numEntered[i]);
}
}

numEntered = getchar();
(1) It can not be assigned to the array itself.
(2) getchar() reads one character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void){
char digits[4] = {0};//4: 3 character + NUL character
int ch, value;
do {
printf("Please enter three digit number 100 to 999: ");
for(int i = 0; i < 3 && (ch = getchar()) != '\n' && ch != EOF; ++i){
digits[i] = ch;
}
if(ch != '\n')
while((ch = getchar()) != '\n')
if(!isspace(ch))//invalid input
*digits = 0;
value = atoi(digits);
} while(value < 100 || 999 < value);
char *rotate_left(char digits[4]);
printf("%d\n", value);
printf("%d\n", atoi(rotate_left(digits)));
printf("%d\n", atoi(rotate_left(digits)));
return 0;
}
char *rotate_left(char digits[4]){
char temp = digits[0];
digits[0] = digits[1];
digits[1] = digits[2];
digits[2] = temp;
return digits;
}

Related

How can I take input character in a character array using %c and produce the right output using %s?

This is my code.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
char ch[100];
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf(" %c", &ch[i]);
}
printf("%s\n", strupr(ch));
return 0;
}
At first, I want to take the size of the character array in n variable. After, i want to take n character's and assign the array. The output comes from this program is right but it also produce some garbage values.
For example:
5
s d g h f
Output: SDGHFC└U▄■`
How can i ignore the garbage values from my output?
Simply initialize your array ch[] to all zeros. I.E.
for (i = 0; i < 100; i += 1) { ch[i] = '\0'; }
Put this line just after the declaration of ch[].
As you are reading character the spaces you are providing in your input, will also be considered as characters, and strupr(c) will give some shaggy output, also you have to manually provided null character at the end of your character array. Below program might help you find your answer
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
for(i = 0; i < n; i++){
char temp;
scanf("%c", &temp);
if(temp != '\n')
ch[i] = temp;
else
break;
}
ch[n] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Your Input should look like
5
sdghf
To give input with spaces. Program will look like.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
char temp;
i = 0;
while(scanf("%c", &temp)){
if(temp == ' ')
continue;
if(temp != '\n')
ch[i++] = temp;
else
break;
}
ch[i] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Now, you can give your character in any arrangement as you want.

Keep characters in an array

I want to do a program that ask to the user to give one character, then enter... until he wants to stop by pressing enter and no caracters.
Then, the program will say: "you gave the caracters ...."
for example:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
result: You gave the caracters: kl
My code doesnet work because when i just press enter, nothing happen. Here is the code:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}
You can do it with c = getchar(); or c = fgetc(stdin) function:
#include <stdio.h>
#define N 1000
int
main ()
{
int i = 0;
int j = 0;
int c;
char str[N];
while (1)
{
c = fgetc(stdin); // or c = getchar();
if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
This is my string!
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!
Or you can use your original scanf("%s", &str1);
#include <stdio.h>
#define N 1000
int main ()
{
int i = 0;
int k = 0;
int c;
int len;
char str[N];
char str1[N];
scanf("%s", &str1);
len = strlen(str1);
for(k = 0; k < len; k++)
{
c = str1[k];
if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
12345
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345
As stated in this answer scanf will not return until you give it a string, i.e. it skips whitespace.
As suggested in the answer and in general, using fgets is the better option.
Edit: A way to accomplish what you want would look like this:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
do {
printf("element number str[%d] : ", i);
fgets(&str[i], 3, stdin);
i++;
} while (str[i - 1] != '\n');
printf("The string is: ");
while (i > j) {
printf("%c", str[j]);
j++;
}
return 0;
}
In the fgets you use the number 3 because pressing enter gives both a newline character [/n] and a return carriage [/r].

Maximum number of Characters in a character array

//Program to find max occurring character in string
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100 // Maximum string size, change to make string smaller or larger
#define MAX_CHARS 255 // Maximum characters allowed for characters
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do{
clrscr();
i=0;
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
i++;
}
// Finds maximum frequency of character
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i; //to print no. of times
}
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
}while(ch=='Y'||ch=='y');
}
When I give it the input: "aaaaeeee", the output is "a" occurring 4 times, but "e" occurs 4 times too. I know this is sorted by ascii values and thats why it gives "a" as output, but what can I do in this program that the output gives both "a" and "e" as output when a case like this occurs?
Add max calculation ahead
i = 0;
max = 0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1;
if (freq[ascii] > max) max = freq[ascii]; // <==== here
i++;
}
Note that this is the max number of the same character you might have.
Then display all chars which maximum is equal to max
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
To fix the endless loop, before the while add char c ; while ((c = getchar()) != EOF && c != '\n');
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n'); // <== note the ';'
} while(ch=='Y'||ch=='y');
Note that you shouldn't use gets, reason is explained here.
Whole code:
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do {
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
for(i=0,max=0 ; str[i] != '\0' ; i++)
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
if (freq[ascii] > max) max = freq[ascii];
}
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n');
}while(ch=='Y'||ch=='y');
}
Above this line
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
Delete it and add this code
for(i=0;i<MAX_CHARS;i++)
{
if(freq[i]==freq[max])
{
printf("\nMaximum occurring character is '%c' = %d times.", i, freq[i]);
}
}

C programming Hex to Char

What I'm trying to do is have the user input a hex number this number will then be converted to a char and displayed to the monitor this will continue until an EOF is encountered.I have the opposite of this code done which converts a char to a hex number. The problem I'm running into is how do i get a hex number from the user I used getchar() for the char2hex program. Is there any similar function for hex numbers?
this is the code for the char2hex program
#include <stdio.h>
int main(void) {
char myChar;
int counter = 0;
while (EOF != (myChar = getchar())) {
/* don't convert newline into hex */
if (myChar == '\n')
continue;
printf("%02x ", myChar);
if (counter > 18) {
printf("\n");
counter = -1;
}
counter++;
}
system("pause");
return 0;
}
this is what i want to the program to do except it would do this continuously
#include <stdio.h>
int main() {
char myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
any help would be appreciated
thank you
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
int myChar;
int counter = 0;
char buff[3] = {0};
while (EOF != (myChar = getchar())) {
if(isxdigit(myChar)){
buff[counter++] = myChar;
if(counter == 2){
counter = 0;
myChar = strtol(buff, NULL, 16);
putchar(myChar);
}
}
}
printf("\n");
system("pause");
return 0;
}
Because chars and ints can be used interchangably in C, you can use the following code:
int main(void) {
int myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
If you want it to loop then just enclose it in the while loop as in your example code.
Edit: You can try out the working code here http://ideone.com/yyvz85

int array doesnt get char values

I am absolutely brand new at programming and im not sure how to explain what im doing here.
The whole purpose of this piece is to enter values and then print them out in the same order. Now I wanna quit from entering values when pressing 'q' and so I have to scanf for chars but when I assign them back to the int array the values are not the same.
Hope that makes any sense to you but in any case heres my code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5000
define flush fflush(stdin)
main() {
int input[SIZE] = {0},i = 0;
int counter = 0;
char inputs, quit;
do {
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
flush;
scanf("%c",&inputs);
flush;
if (inputs == 'q')
quit = 'q';
else {
input[i] = inputs;
counter++;
i++;
}
} while (i < SIZE && quit != 'q');
for(i = 0; i < counter; i++){
printf("%i.%i\n", i + 1, input[i]);
}
system("pause");
}
Ive been trying to do this on my own btw and also researched some information online regarding chars but couldnt find anything that would help me. Thanks a lot in advance.
You should nor be getting integer through %c neither assign char values to integers variables when that is not the intention, rather you should approach something like this
i = 0;
do {
printf("Enter a number: ");
scanf("%d", &input[i]);
i++; counter++;
printf("Do you want to continue? (y/n) : ");
scanf("%c", &inputs);
} while(inputs == 'y');
or u can get the number of integer inputs upfront and loop to get that much integers.
try instead (using your original code as much as possible):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 5000
int main()
{
int input[SIZE] = {0},i = 0;
int counter = 0;
char inputs[32];
bool quite = false;
do
{
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
// read a string from user, then convert when appropr
fgets(stdin, sizeof(inputs), inputs);
if (inputs[0] == 'q')
{
quit = true;
}
else if ( isdigit(inputs[0]) )
{
input[i] = atoi(inputs); // this will disregard any ending \n
counter++;
i++;
}
}
while (i < SIZE && !quit);
for(i = 0; i < counter; i++)
{
printf("%i.%i\n", i + 1, input[i]);
}
system("pause");
}
Another variant. This one will read in characters regardless of the use of whitespaces, since it uses getchar() rather than scanf(). I'm not sure if this is what you want. It seems as though you want integers but are reading characters. So this solution may be completely off base.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5000
int main()
{
char input[SIZE] = {0};
int i = 0;
int counter = 0;
char inputs;
printf("Input number ('q' to quit and display numbers entered): ");
while (((inputs = getchar()) != EOF) && (counter < SIZE))
{
if (inputs == 'q')
break;
input[counter] = inputs;
counter++;
}
for(i = 0; i < counter; i++)
{
printf("%c\n", input[i]);
}
system("pause");
return 0;
}
If you do really want ints, this one should work.
Notice that the atoi() function can be used to convert a C-string to an int.
The fgets() function is used to read the C-string from STDIN. However, scanf("%s", input); would also work here, as opposed to the scanf("%c", &inputs); that you used.
#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 1000
#define SIZE 5000
int main()
{
char input[INPUT_SIZE] = {0};
int numbers[SIZE] = {0};
int i = 0;
int counter = 0;
while ((fgets(input, sizeof(input), stdin) != NULL) && (counter < SIZE))
{
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
if (input[0] == 'q')
break;
numbers[counter] = atoi(input);
counter++;
}
for(i = 0; i < counter; i++)
{
printf("%i\n", numbers[i]);
}
system("pause");
return 0;
}

Resources