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;
}
Related
problem
After receiving the string S, write a program that repeats each character R times to create a new string and print it out. That is, you can make P by repeating the first character R times and repeating the second character R times. S contains only the QR Code "alphanumeric" characters.
QR Code "alphanumeric" character is 0123456789ABCDEFGHIJK
Input
The number T (1 ≤ T ≤ 1,000) of test cases is given in the first line. Each test case is given by dividing the number of repetitions R (1 RR 88) and the string S into spaces. The length of S is at least 1 and does not exceed 20 characters.
Output
Output P for each test case.
input Example
2
3 ABC
5 /HTP
output Example
AAABBBCCC
/////HHHHHTTTTTPPPPP
My code:
#include<stdio.h>
int main() {
int a=0;
scanf("%d", &a);
for (int k = 0; k < a; k++) {
int d;
char b[20];
scanf("%d", &d);
scanf("%s", &b);
for (int i = 0; b[i]!=NULL; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
}
}
There is a problem in the code:
scanf("%s", b);
we write "b" instead of "&b"
‘&’ is used to get the address of the variable. C does not have a string type, String is just an array of characters and an array variable stores the address of the first index location.By default the variable itself points to the base address and therefore to access base address of string, there is no need of adding an extra ‘&’
so we can write :
#include<stdio.h>
int main() {
int a=0;
scanf("%d", &a);
for (int k = 0; k < a; k++) {
int d;
scanf("%d", &d);
char b[20];
scanf("%s",b);
for (int i = 0; b[i]; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
printf("\n");
}
}
Improvements
Use size_t to iterate through arrays
NOTE: char b[20];, b decays to pointer (sizeof() operator is an exception)
In line scanf("%s", &b);, &b is not required it will cause undefined behavior, just b is fine
Always check whether scanf() input was successful
Don't use "%s", use "%<WIDTH>s", to avoid buffer-overflow
b[i]!=NULL is quite wrong, NULL is a pointer whereas b[i] is a char, and char can't be compared with pointer, you should check for '\0' or just 0
Initialize your variable b using = {}, then all the elements of b will be 0
Length of b should be 21 +1 for the null terminating character
Final Code
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 0;
if (scanf("%d", &a) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
for (int k = 0; k < a; k++) {
int d;
if (scanf("%d", &d) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
char b[21] = {};
if (scanf("%20s", b) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
for (size_t i = 0; b[i] != 0; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
puts("\n");
}
return EXIT_SUCCESS;
}
Input
2
3 ABC
5 /HTP
Output
AAABBBCCC
/////HHHHHTTTTTPPPPP
TRY IT ONLINE
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;
}
I am trying to write a function to divide a string in half but after the initial input it does not output anything. My goal is to scan a year and save the first two number and the last two numbers. This is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
// Function to print n equal parts of str
void divideString(char *str, int n) {
int str_size = strlen(str);
int i;
int part_size;
if (str_size % n != 0) {
printf("Invalid Input: String size");
printf(" is not divisible by n");
return;
}
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
}
int main() {
char year_number;
scan_year2();
char str = year_number;
divideString(str, 2);
getchar();
return 0;
}
Assuming that a year is at least a 3-digit number, the best way to treat it is to treat it as a number, not as a string:
...
int year;
scanf("%d", &year);
int first = year / 100;
int last = year % 100;
printf("%d %d\n", first, last);
...
dont ignore compiler warnings, it must be complaining at you about this
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
you try to return twice.
Also
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
is not going to give you the correct output. YOu are outputing the string each time. IE if str = "1923" then you will get
1923923
232
You should do
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%c", str[i]);
}
to only output one char at a time
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;
}
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;
}