Stumped on ASCII art challenge - c

all,
I'm working on some of the challenges at CodinGame.com and I'm having some trouble with a challenge that requires me to display a letter in ASCII form using a loop of rows with "#"s and spaces where each "letter" is 3 characters long and 5 tall. For example:
Line 1 = " # "<br>
Line 2 = "# #"<br>
Line 3 = "###"<br>
Line 4 = "# #"<br>
Line 5 = "# #"<br>
Here is the relevant code for the program up to now:
int L; // Length of ASCII art char, always 3
scanf("%d", &L); // <- CodinGame scanf's all values from case into stdin
int H; // Height of ASCII art char, always 5
scanf("%d", &H); fgetc(stdin);
char T[257]; // <- Characters that must be turned into ASCII art
char lclcpy[1025]; // <- Copy array for me to use outside of loop.
fgets(T, 257, stdin); // <- T is drawn from case to stdin
for (int i = 0; i <= H; i++) {
char ROW[1025]; // <- String containing the current row of "#"s and spaces
strncpy(lclcpy, ROW, sizeof(lclcpy)); // <- I copy the row into my local copy.
fgets(ROW, 1025, stdin); // <- Program draws ROW into its stdin.
fprintf(stderr, "%s", lclcpy); // <- I print out the value of ROW on this line alone to debug. CodinGame uses stderr for debugging purposes.
}
Once the loop is complete, I end up with the alphabet in ASCII art, which is what my lclcpy looped through and printed.
What I want to do is copy only the segments of the big ASCII art image that correspond to a specific letter. I was able to do this in C++ because strings make life worth living, but I'm tearing my hair out trying to do this in C.
I figure I'd create an array of character pointers, with each element of the array pointing to the segments of ROW/lclcpy that contain a letter's data. Unfortunately, I've had no luck trying to do anything with character pointer arrays or two-dimensional character arrays. I keep getting segfaults and other memory problems. I'm not comfortably familiar with pointers yet. Seems I can only think in string mode, and nothing I've found has helped. Any help is greatly appreciated. Please consider my lack of experience. Thank you.

Related

Why I cannot access the first read char array after reading a series of others in C?

I wanted to read a phrase and a series of numbers/alphabetic separated by ",". I read the first string then I print it (works fine). I read the first string, read 62 of those series and try to print the first string again and is not working. I tried a lot of methods but none working.
char text[1001];
scanf("%[^\n]", text);
for (int i = 1; i <= 62; i++) {
char alpha[3] = {0}, lit_orig, lit_replace;
scanf("%s", alpha);
lit_orig = alpha[0];
lit_replace = alpha[2];
}
printf("\n%s", text);
Input example:
Example text here!
a,H b,j c,6 d,I e,2 f,R g,5 h,t i,h j,k k,m l,f m,D n,F o,1 p,0 q,c r,G s,n t,N u,e v,B w,r x,U y,p z,A A,8 B,X C,S D,P E,T F,a G,M H,d I,K J,L K,3 L,C M,i N,9 O,E P,w Q,o R,z S,4 T,O U,q V,V W,J X,x Y,Z Z,u 0,l 1,y 2,W 3,s 4,Q 5,g 6,v 7,7 8,b 9,Y
Output example: There is no output.
I did expect it to print just fine the first string called "text" but it is not working. I tried even clearing out the buffer using getchar() but no results (this is what other websites said it would work). Can you explain what is wrong with my code?
Taking into account this code snippet
lit_orig = alpha[0];
lit_replace = alpha[2];
where there is used the index equal to 2 it seems that in the call of scanf
scanf("%s", alpha);
you are entering three characters. As a result the terminating zero character '\0' is written outside the array alpha in the memory occupied by the array text. As a result the array text contains an empty string.
You need to declare the array alpha at least like
char alpha[4] = {0},
And use the format string in the call of scanf the following way
scanf("%3s", alpha);
Your alpha is too small for what you are doing.
Change to char alpha[5] for a quick fix.
Insert an output inside your loop to be aware of what is happening.
printf ("(%4s)", alpha);
Then fine tune your access and use of alpha.
Note the "()" I added to the debug output, to make sure that you see whether/where white space is. I think it might surprise you.

How am I supposed to know when to stop receiving user inputs in C?

This is the task given:
Write a program that encrypts the text from the input by using an easy
substitution method. The only allowed characters in input are letters
'A'-'Z', whitespace and a newline character. What is a substitution
method using ciphertext alphabet? It is easy, let us follow the
example:
Standard English alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ Ciphertext
alphabet: ZEBRASCDFGHIJKLMNOPQTUVWXY
Text to be encrypted:
BEST UNIVERSITY FOR YOU
We replace each letter from the input text with the appropriate letter
from ciphertext, e.g., A is replaced with Z, B is replaced with E, C
is replaced with B, and, e.g., M is replaced ith J, etc. Thus, we
get:
EAPQ TKFUAOPFQX SLO XLT
So, Input consists of two parts, in the first line there is a
ciphertext, that is a string of length 26 consisting of non-repeating
letters 'A','B',...,'Z' (English 26 letters), in some order. In the
second part of the input, i.e., in the successive lines, there is a
text consisting of letters ('A'-'Z'), whitespace and a newline
character.
You have to print enciphered input text, as follows: each letter from
input substitute with the appropriate letter from the ciphertext,
leaving whitespaces and newline characters.
Example:
Input:
ZEBRASCDFGHIJKLMNOPQTUVWXY FLEE AT ONCE WE ARE DISCOVERED
FLEE AT ONCE WE ARE DISCOVERED
Output:
SIAA ZQ LKBA VA ZOA RFPBLUAOAR SIAA ZQ LKBA VA ZOA RFPBLUAOAR
I have already written the code for encrypting the text. It works as intended, in the beginning I thought I had only two lines of input. When I submit it like that, I get an unspecified error.
#include <stdio.h>
#include <string.h>
int main() {
int i, len1, len2, j;
char toenc1[40], toenc2[40], enc[27], alph[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
fgets(enc, 40, stdin);
fgets(toenc1, 40, stdin);
fgets(toenc2, 40, stdin);
len1 = strlen(toenc1); //
len2 = strlen(toenc2);
for (i = 0 ; i < len1 ; i ++){
for (j = 0; j < 27 ; j++){
if (toenc1[i] == alph[j]){
toenc1[i] = enc[j];
j=26;
}
}
}
for (i = 0 ; i < len2 ; i ++){
for (j = 0; j < 27 ; j++){
if (toenc2[i] == alph[j]){
toenc2[i] = enc[j];
j=26;
}
}
}
printf("%s", toenc1);
printf("%s", toenc2);
return 0;
}
In the second part of the input, i.e., in the successive lines is what caught me off-guard. I don't know how to deal with this part.
In the second part of the input, i.e., in the successive lines is what caught me off-guard. I don't know how to deal with this part.
Presumably, the concept you are struggling with is that there might be a limited number of successive lines. Nevertheless, it is true, just as much when the program is reading from its standard input as when it reading from a file on disk (and indeed, the standard input might be from a file on disk). Surely you recognize that a disk file has a fixed length, so if you keep reading from it then eventually you will reach the end.
Having accepted that you can read the input to its end, at least in principle, the easier part is finding out how to detect when you have in fact gotten there. That's easier, because you can just read the documentation of your chosen input function (fgets() in this case) to find out what it does under those circumstances. For example, its manual page says, in part:
gets() and fgets() return [...] NULL on error or when end of file occurs while no characters have been read.
That tells you what you need to know to solve the problem. And it also tells you something you need to know to write robust code that uses fgets() in less controlled environments, where the input might not always have the form you expect.

I am trying to create a program that takes a name and outputs the initials but keep running into an array error

I am trying to create a program that take the input from the user and prints the first character of each word but every time I try to Here is my code.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
char leng[100];
int len;
scanf("%s", &leng[100]);
len = strlen(&leng[100]);
char name[len];
//checking if at end or not
while (name[len] != '\0')
{
if (name[len] == ' ')
printf("%c", name[len + 1]);
len++;
}
}
Every time I give a name it shows an error something like:
index 3 out of bounds for type 'char [len]'
These two lines are incorrect:
scanf("%s", &leng[100]);
len = strlen(&leng[100]);
If you translate these into English, their meanings as written are:
Scan a string to the memory at the address of 101st element of the
leng array.
Get the length of the string that starts at the address
of the 101st element of the leng array.
The array index is out of bounds because leng[100] is past the end of the array. Remember that a 100 element array goes from 0 to 99, not from 1 to 100!
You want to be scanning into the base address of the array, and passing the base address of the array into strlen(). I'll leave the syntax for you to figure out from your textbook.
And by the way, you also have a problem in your code because you're reading your data into an array named leng, but your loop is working with an array named len. There are at least two additional problems in your code, but I'll leave them for you to debug.
There are a few things to consider with your code. As #richardschwartz already mentioned, you are not referencing your char arrays correctly. you have:
scanf("%s", &leng[100]);
len = strlen(&leng[100]);
You may want the following instead:
scanf("%s", leng);
len = strlen(leng);
Also, keep in mind that scanf with the %s flag will stop reading input once white-space is detected. For example, if you input "hello world",
scanf("%s", leng);
will only catch the characters "hello". To get around this, you could loop scanf to read multiple words and return the first character of each word as you desire.
Lastly, scanf is not advised for beginners though. See paxdiablo's excellent reason regarding lack of overflow protection, here: https://stackoverflow.com/a/1248017/6870832

fgets has more characters that its supposed to

Hi I'm trying to use fgets to take the string from stdin and store it in input, then it should compare with an array of words (over 50000 words long taken from a text file) using the strcmp method, but i could never get them to compare for some reason until I found out why here is my code.
char[] text;// <----------array is already full and working at this point I just
char input[24];// thought I'd include this for the memcpy
char check[24]="happ";
fgets(input,24, stdin);
for(int i=0; i < 50000; i++){
memcpy(check, text[i], strlen(input));// this is supposed to get a substring
if(strcmp(check, input) == 0){// this is supposed to auto complete
printf("%s",text[i]);}// say for example 4 letters are inputted the entire
//array will be checked if they have the same letters then that word will be printed
printf("\n %lu %s\n",strlen(check),check);
printf("\n %lu %s\n",strlen(input),input);
if "happ" is inserted it should print out the last letter in the array and its
size which it should be 4 but stdin "5 happ" I thought there might be a \n
at the end of input so i used a temp and got the substring of input at length
strlen(input)-1 but all i got was "6 happ\377" please help I tried researching it but I didnt understand what was wrong with it so I didn't know what to research
I was able to find the answer finally it was a simple fix
int cch=strlen(input-1);
if (cch > 1 && input[cch-1] == '\n')
input[cch-1] = '\0';

How to sort characters in a string alphabetically using scanf() and saved character in buffer? [duplicate]

This question already has answers here:
What would be the simplest way to alpha sort an array of chars in C?
(7 answers)
Closed 7 years ago.
Hi I'm pretty new to using C.
My teacher told me to code a function to sort characters in a string alphabetically by using array & the fact that when a scanf() a string, the first character is called and the rest are saved in the buffer.
(I haven't learnt about pointers yet.)
For example, if I type in badf and space(signalling "an end", or the sentinel value for end of string), the function should return abdf.
I'm stuck here. It's my first ever stackoverflow question! Please help. Thanks.
#include <stdio.h>
#include <string.h>
int main() {
char arr[100];
char front_char, first_char;
// set the variables
int i, j, k, l;
printf("Enter a string and press space to end\n");
// get the input using scanf, which will just get the first character and save the rest in buffer
scanf("%c", &first_char);
// assign the first_character in arr[0] for initialization
arr[0] = first_char;
// 32 is "space" in ascii code. Space is used as a sentinel value. User is supposed to press space at the end of the String
while(front_char != 32) {
// get the "second" character from buffer and ass. repeat this until the next character in buffer is 32, or "space"
scanf("%c" , &front_char);
// load character from buffer, and check if its assigned number in ascii code is smaller than characters in array
for(i = 1; front_char != 32; i++) {
for(j = 0; j < i; j++) {
// go through the previously aligned array to compare the ascii number of the loaded character from buffer
if(arr[j] <= front_char) {
continue;
} else {
// run through the previously aligned array, and if a character with bigger ascii number comes up,
for(k = i-1; k >= j; k--) {
// assign/push the values in array to the next index(i don't know how to describe this, but I hope you see what I mean..)
arr[k+1] = arr[k];
}
}
// assign the loaded character according its ascii number size
arr[j] = front_char;
}
}
// print the result
for(l = 0 ; l < i ; l++){
printf("%c", arr[l]);
}
}
return 0;
}
To get to your final solution, you have to get through three intermediate steps:
Read in the string successfully
Address individual characters in the string
Transpose characters in the string
You definitely have bugs (ameyCU's answer).
Try first to read in the string, and just print it out again; no other action.
When you've got that, try to read in the string, then print it out character-by-character.
If you can do that, you're ready for step 3 and almost done.
EDIT: also, when you get there,
while(front_char != ' ')
is better than != 32; it's more reliable and much easier to read and understand.
For example, if I type in badf and space(signalling "an end", or the sentinel value for end of string)
You want to take input as string ex-badf but your are taking input in a character variable.
scanf("%c" , &first_char);
Second -
while(front_char != 32)
Checking if front_char is space or not but front_char does not have any value stored in it.
Program will crash as soon as you give input !!

Resources