Character Array User Input Scanf - c

Just started learning programming on my own and whilst trying to create an array of characters from user input, using scanf, have hit the wall; the code is as below:
#include <stdio.h>
#define I 5
int main (void) {
char a[I+1] = {a[I+1] = '\0'}, q;
int i;
for(i = 0; i < I; i++) {
printf("Enter an alphabet:\t");
//scanf("%c", &q);
//scanf("%c*\n", &q);
//scanf("%[^\n]", &q);
//scanf("%[a-z, A-Z]", &q);
scanf("%127[^\n]", &q);
a[i] = q;
}
printf("\n");
for(i = 0; i < I; i++) {
printf("Element a[%d] of a[I]:\t%c\n", i, a[i]);
}
printf("And the a[I] string:\t%s\n", a);
return 0;
}
None of the scanf combinations in the above code works: the program either skips input prompt after the first one or does not store response.
How can this be resolved with scanf?

char a[I+1] = {a[I+1] = '\0'} is not valid. Even if it compiles, it is going out of bounds when assigning the '\0' character. The commonly used convention looks more like this instead:
char a[I+1] = {0};
Or simply:
char a[I+1] = {};
That said, q is only 1 char in size, but your scanf() is trying to read a string up to 127 chars into q. So you are going to trash memory. To read a single char at a time, use %c instead:
#include <stdio.h>
#include <string.h>
#define MAX_INPUT 5
int main (void) {
char a[MAX_INPUT+1];
int i, len;
for(i = 0; i < MAX_INPUT; i++) {
printf("Enter an alphabet:\t");
scanf("%c", &a[i]);
}
a[MAX_INPUT] = '\0';
printf("\n");
len = strlen(a);
for(i = 0; i < len; i++) {
printf("Element a[%d]:\t%c\n", i, a[i]);
}
printf("And the a string:\t%s\n", a);
return 0;
}
Or, you can remove the loop and just use a single call to scanf() using "%5[^\n]" as the format string:
#include <stdio.h>
#include <string.h>
#define MAX_INPUT 5
int main (void) {
char a[MAX_INPUT+1];
char fmt[20];
int i, len;
sprintf(fmt, "%%%d[^\n]", MAX_INPUT);
printf("Enter an alphabet:\t");
scanf(fmt, a);
printf("\n");
len = strlen(a);
for(i = 0; i < len; i++) {
printf("Element a[%d]:\t%c\n", i, a[i]);
}
printf("And the a string:\t%s\n", a);
return 0;
}

This works without any warning or error on Cygwin gcc v7.3 with Wall flag:
#include <stdio.h>
#define I 5
int main (void) {
char a[I+1] = {a[I+1] = '\0'},q;
int i;
for(i = 0; i < I; i++) {
printf("Enter an alphabet:\t");
scanf("%c%*c", &q);
a[i] = q;
}
printf("\n");
for(i = 0; i < I; i++) {
printf("Element a[%d] of a[I]:\t%c\n", i, a[i]);
}
printf("And the string a[I]:\t%s\n", a);
return 0;
}

Related

Create a dynamic matrix of char in c

i want to create a dynamic matix to enter a character , so i start firstly with creating a dynamic matric of int to after switch it to char
the code of the dynamic matrix works correctly :`
#include <stdio.h>
#include <stdlib.h>
int main(){
int r , c , b;
int *ptr, count = 0, i;
printf("ROWS ");
scanf("%d",&r);
printf("COLS ");
scanf("%d",&c);
ptr = (int *)malloc((r * c) * sizeof(int));
for (i = 0; i < r * c; i++)
{
scanf("%d",&b);
ptr[i] = b;
}
for (i = 0; i < r * c; i++)
{
printf("%d ", ptr[i]);
if ((i + 1) % c == 0)
{
printf("\n");
}
}
return 0;}
but when i did this change to switch it to matrix of char it doesn't read all the charecter so it stopped reading before the matrix finish
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r , c ;
int count = 0, i;
char *ptr,b;
printf("ROWS ");
scanf("%d",&r);
printf("COLS ");
scanf("%d",&c);
ptr = (char *)malloc((r * c) * sizeof(char));
for (i = 0; i < r * c; i++)
{
scanf("%c",&b);
ptr[i] = b;
}
for (i = 0; i < r * c; i++)
{
printf("%c ", ptr[i]);
if ((i + 1) % c == 0)
{
printf("\n");
}
}
return 0;
}
It seems you need to write
scanf(" %c",&b);
^^^^
to skip white space characters including the new line character '\n' that corresponds to the pressed Enter key.
That is when the format string starts from the space character white space characters are skipped.
Pay attention to that you should free the allocated memory when the dynamically allocated array is not needed any more.
Otherwise if you want to read also spaces in the array then you can rewrite the for loop the following way
for (i = 0; i < r * c; i++)
{
do scanf("%c",&b); while ( b == '\n' );
ptr[i] = b;
}

rearranging a char array with strncpy in C

I am trying to change the sorting of a the arr list which could consist of zero, one, two as the inputted and stored values for arr. The stringreplace function is meant to shift every single element by one so the new sorting would be one, two, zero. I am trying to replace the elements with one another by using the strncpy function but I think it is a bit faulty, how could i fix this?
strncpy function
char stringreplace( char a[], int b){
for(int j = 0; j > b -1; j++){
strncpy(a[j], a[j+1], sizeof(a));}
for(int j = 0; j > b; j++){
printf("%s",a[j]);}
}
main function
int main()
{
char input[100];
char arr[100]= {0};
int number;
printf("Input the number of strings: ");
scanf("%d", &number);
for(int i= 0; i < number; i++){
printf("Input the number of strings: ");
scanf("%s", input);
arr[i] = input;
}
stringreplace(arr, number);
return 0;
}
You may consider allocating strings dynamically, assigning a pointer for each string into an array words, and then rotating each pointer in the array to the left.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void lrot_words(char *words[], int n);
int main(void)
{
char *p, word[100], *words[100];
int i, num_words;
printf("Enter the number of words: ");
scanf("%d", &num_words);
for(i = 0; i < num_words; i++){
printf("Enter a word: ");
scanf("%s", word);
if ((p = malloc(strlen(word) + 1)) == NULL) {
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
words[i] = strcpy(p, word);
}
lrot_words(words, num_words);
for (i = 0; i < num_words; i++) {
printf("%s\n", words[i]);
}
return 0;
}
void lrot_words(char *words[], int n)
{
char *temp = words[0];
int i;
for (i = 0; i < n - 1; i++) {
words[i] = words[i+1];
}
words[i] = temp;
}

Find missing lower-case letters that are not in a series of words

As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}

Arranging a character array using bubble sort

Here is my code so far. I am perfectly able to sort files holding numbers but clueless when it comes to characters. It takes in a file of my choosing and outputs another file with the sorted array. But so far all I'm getting are blank files and I can't figure out why.
So how can I fix my code to sort an array of characters and then output it?
#include <stdio.h>
int bubble_sort(char *a, int n);
int main(void) {
char a[10];
int n = sizeof a / sizeof a[10];
int i;
char inname;
char outname;
printf("Enter input name: ");
scanf("%s", &inname);
printf("Enter output name: ");
scanf("%s", &outname);
FILE *in, *out;
out = fopen(&outname, "w");
if ((in = fopen(&inname, "r")) == NULL) {
printf("File not found\n");
}
else {
for (int i = 0; i < 10; i++)
{
fscanf(in, "%s ", &a[i]);
}
bubble_sort(a, n);
for (i = 0; i < 10; i++) {
printf("%s\n", a[i]);
fprintf(out, "%s\n", a[i]);
}
}
fclose(in);
fclose(out);
return 0;
}
int bubble_sort(char *a, int n) {
int i, j;
char temp;
for (j = 1; j<n; j++)
{
for (i = 0; i<n - j; i++)
{
if ((int)a[i] >= (int)a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
return a[i];
}
The basic problem, as I can see, is with
scanf("%s", &inname);
In your code, inname is a single char, which cannot hold string inputs. You'll be needing an array.
You need to change
char inname;
char outname;
to
#define NAMSIZ 32
char inname[NAMSIZ] = {0};
char outname[NAMSIZ] = {0};
and then,
scanf("%31s", inname);
and accordingly.
Same problem exist with fscanf(in, "%s ", &a[i]);, too.

read input character and print the occurrence in graphical format

I am reading the input and trying to print all the input lowercase character in a graphical format, am able to read it and keep track of the number of time each character repeats but not able to print it in a graphical way,can u pls help me out. Here is my code
#include <stdio.h>
#include <ctype.h>
int print_fun(int);
int main() {
int ch = 0, i = 0;
int char_count[26] = {0};
printf("\nNOTE:PRESS * TO EXIT\n");
while((ch = getchar()) != '*') {
if(islower(ch))
char_count[ch - 'a']++;
}
printf("\n");
for(i = 0; i < 26; i++)
//printf("%c:%d\n",'a'+ i, char_count[i]);
//printf("%c:\n", 'a'+ i, print_star(char_count[i]));
printf("%c:\n",print_star(char_count[i]),'a'+ i);
printf("\n");
return 0;
}
int print_star(int value) {
int i = 0;
for(i = 0; i < value; i++)
printf("*");
}
o/p: aaxyyz
a:**
b:
c:
...
...
x:*
y:**
z:*
Your printf call is missing an format argument, you have this:
printf("%d:%c\n",print_star(char_count[i]),'a'+ i);
but you are passing two arguments to printf, as far as I can tell this is what you meant:
printf("%d:%c\n",print_star(char_count[i]),'a'+ i);
Also, print_star has a return value of int but you do not have a return statement, I think you meant to return i and in that case you should add:
return i ;
at the end. The behavior without a return at the end is undefined. Finally, it looks like you have a typo in forward declaration, this:
int print_fun(int);
should be:
int print_star(int value );
#include <stdio.h>
#include <ctype.h>
//int print_fun(int);
void print_star(int);
int main(void){
int ch = 0, i = 0;
int char_count[26] = {0};
printf("\nNOTE:PRESS * TO EXIT\n");
while((ch = getchar()) != '*'){
if(islower(ch))
char_count[ch - 'a']++;
}
printf("\n");
for(i = 0; i < 26; i++){
printf("%c:",'a'+ i);
print_star(char_count[i]);
printf("\n");
}
printf("\n");
return 0;
}
void print_star(int value){
int i = 0;
for(i = 0; i < value; i++)
printf("*");
}

Resources