program stops working if i use a value used by user - c

#include<stdio.h>
//prints a shape using users input
int main() {
int i, j ;
char a ;
i = 0 , j= 0;`
printf("enter your charecter :");
scanf("%s", &a);
for ( j = 0; j < 5; j++) {
for ( i = 0; i < 5; i++) {
printf("%s", a);
}
printf("\n");
}
return 0;
}
program stops after input by user

&a does not refer to a string. %s will write all characters entered and nul terminate so will overrun the the single character to which &a refers.
You have the same format specifier mismatch for the output. The format specifier for a single character is %c, however in this case you could use getchar() / putchar().

Related

I don't know why I got it wrong in my code. c language, string iterations

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

The for loop in C is not executed

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)"

C program to limit the count of characters entered by user. Need Solution?

I am getting space between input array and output array, WHY?
[#include <stdio.h>
int main()
{
int i, j;
char str\[99999\];
scanf(" %d", &i);
for (j = 0; j <= i; j++)
{
scanf("%c", &str\[j\]);
}
for (j = 0; j <= i; j++)
{
printf("%c", str\[j\]);
}
return 0;
}
OUTPUT
3
harsh
//Why This Space??
har
This is because you are processing 4 characters with indices 0,1,2,3.
Your input characters are : 3EnterharshEnter
The first scanf("% d",...) read only the 3 and leaves the other characters in the input buffer then you read the 4 characters \n, h, a, r... and print a new line followed with har

Simple code program to print ASCII of a string (per characters) not working with input cases

So i have created a simple program to print ASCII codes of a string per characters, in this case i must use input case(T) to toggle on how much string that i want to print to ASCII.
There are 2 problems:
The first problem is it wont read all of my input case and only read the last case of string (it was supposed to print every ASCII code of every string). The second problem is i must use "-" symbol between every ASCII but it ended up in the end of every ASCII code that is printed.
What is wrong and what should i do in this case? I am still not very fond of C Programming so i couldn't seem to find any solution for this. Here is the the code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int T;
char t[1000];
scanf("%d", &T);
for(int i = 0; i < T; i++)
{
scanf("%s", t);
fflush(stdin);
}
for(int i = 0; i < T; i++)
{
printf("Case %d:\n", i+1);
for(int j = 0; t[j] != '\0'; j++)
{
printf("%d-", t[j]);
}
printf("\n");
}
return 0;
}
And here is the result of the program when run:
2
ABCDEF
GHIJKL
Case 1:
71-72-73-74-75-76-
Case 2:
71-72-73-74-75-76-
--------------------------------
Process exited after 9.87 seconds with return value 0
Press any key to continue . . .
The second inner for loop must be inside the first for loop.
Also the call of the function fflush
fflush(stdin);
has undefined behavior.
The body of the function main can look like
size_t n;
char s[1000];
scanf( "%zu", &n );
for ( size_t i = 0; i < n; i++ )
{
scanf( "%s", s );
printf( "Case %zu:\n", i+1 );
for ( size_t j = 0; s[j] != '\0'; j++ )
{
if ( j != 0 ) putchar( '-' );
printf( "%d", s[j] );
}
printf("\n");
}

Why scanf or fgetc does not work as expected

Following is my code and it is not stopping for first index and I wonder why ? Same is the result with scanf
#include<stdio.h>
void main()
{
int n = 0, i = 0;
char arr[10];
printf("How many characters do u want to enter ");
scanf("%d", &n);
//printf("\n\t%d", n);
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin);
arr[i] = ch;
//putchar(arr[i]);
}
i = 0;
printf("You have entered characters are \n");
for(i = 0; i < n; i++)
{
printf("arr[%d] = %c\n", i, arr[i]);
}
printf("\n");
}
When I run this code I get following
How many characters do u want to enter 5
Enter 0 character-->
Enter 1 character-->
program does not wait for first character to input.
There is an endline character on the input stream that is left there by scanf("%d",&n) and is read by the first fgetc
Same is the result with scanf
Are you using scanf correctly? Try the following (don't miss the space before the %c):
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
scanf(" %c", &arr[i]);
}
Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.
So, when fgetc starts reading from STDIN, it reads a character and leaves the newline character. So you should either use scanf() i.e. scanf(" %c", &arr[i]); as suggested by Cubbi. Or you need to discard that newline character otherwise. You may use this
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin); // newline is consumed here
if(ch=='\n')
ch = fgetc(stdin); // you get the expected value
arr[i] = ch;
//putchar(arr[i]);
}

Resources