The problem is my code doesn't execute the for loop. It's just taking one input and printing it.
#include<stdio.h>
int main(){
int A[100], B[100], C[100], D[100];
int r[100];
for(int i = 0; i < 3; i++)
{
scanf("(%d+%d)x(%d-%d)", &A[i], &B[i], &C[i], &D[i]);
r[i] = (A[i]+B[i])*(C[i]-D[i]);
}
for(int k = 0; k < 3; k++)
{
printf("%d", r[k]);
}
return 0;
}
Assuming you input expressions are separated by a newline, when the second call to scanf is made, the first unread character is a newline rather than a left parenthesis. To make scanf skip leading whitespace characters, start the format string with a space, i.e. " (%d+%d)x(%d-%d)".
https://pubs.opengroup.org/onlinepubs/000095399/functions/fscanf.html
First a fall this is the wrong way to use scanf.
use the below code:-
#include<stdio.h>
int main(){
int A[100], B[100], C[100], D[100];
int r[100];
for(int i = 0; i < 3; i++)
{
scanf("%d %d %d %d", &A[i], &B[i], &C[i], &D[i]);
r[i] = (A[i]+B[i])*(C[i]-D[i]);
}
for(int k = 0; k < 3; k++)
printf("%d", r[k]);
return 0;
}
The problem is you do not skip the pending newline when reading the second line of input, so the newline does not match ( and scanf() returns 0.
You should always test scanf() return value to ensure input was validly converted.
Also make sure each result is printed as a separate number by appending a space or a newline.
Here is a modified version:
#include <stdio.h>
int main() {
int A[100], B[100], C[100], D[100];
int r[100];
int n = 0;
for (int i = 0; i < 3;) {
/* ignore pending spaces */
if (scanf(" (%d+%d)x(%d-%d)", &A[i], &B[i], &C[i], &D[i]) == 4) {
r[i] = (A[i] + B[i]) * (C[i] - D[i]);
n = ++i;
} else {
int c;
/* flush pending input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
break;
printf("Invalid input, try again:");
}
}
for (int k = 0; k < n; k++) {
printf("%d\n", r[k]);
}
return 0;
}
i fixed it with Add a space before the first ( inside the scanf " (%d+%d)x(%d-%d)"
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 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;
}
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.
When I run this program with a file imported into Xcode, I receive an error of Thread 1: EXC_BAD_ACCESS (code=1 address=0x68) at the line c = fgetc(ptr);. I am not sure why fptr is null when it gets to this line. Any help would be great thanks.
#include <stdio.h>
#define M 100
#define N 100
char array[M][N] = {0};
void readFile();
void findStartandEnd();
void mazeTraversal();
int m = 0;
int n = 0;
int start[2] = {0};
int end[2] = {0};
int main() {
readFile();
//findStartandEnd();
//mazeTraversal();
}
void readFile() {
FILE *fptr;
char c;
char file_name[20];
int i, j;
printf("Please enter the size of the MxN maze.\n");
printf("Start with the M size then the N size follow each number by the return key.\n");
scanf("%d", &m);
scanf("%d", &n);
printf("Type in the name of the file containing the Field\n");
scanf("%s", file_name);
fptr = fopen(file_name, "r");
for (i = 0; i < M && i < m; i++)
for (j = 0; j < N && j < n; j++) {
c = fgetc(fptr);
while (!((c == '1') || (c =='0')))
c = fgetc(fptr);
array[i][j] = c;
}
fclose(fptr);
for (i = 0; i < M && i < m; i++)
for (j = 0; j < N && j < n; j++) {
if (j == 0) printf("\n");
printf("%c ", array[i][j]);
}
printf("\n");
}
You do not test if scanf correctly parsed a string into file_name. You do not even protect file_name from a potential buffer overflow with scanf("%19s", file_name);
Furthermore, you do not test whether fopen succeeded at opening the file. fptr could be NULL for many possible reasons, you must test that and fail gracefully.
Note that scanf will stop at the first white space character after the first word. Filenames with embedded spaces cannot be entered with this method.
Note also that c should be defined as int instead of char to properly test for end of file as EOF returned by fgetc() does not fit in a char.
You should also use braces around non trivial statements commended by the for loops. They are not strictly necessary, but it will avoid silly bugs when later amending your code.
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("*");
}