Inverted Triangle from String - c

I'm a bit confused on how to make an inverted triangle from user input so that the last character is removed each time and a space is added to the front of each row. So this is what I have now, it should be correct minus the spaces (which I can't seem to get to work for whatever reason). Should be a really simple for loop, but I just can't figure it out for the life of me.
Here's what it looks like when it's run now:
Enter a string: EXAMPLE
E X A M P L E
E X A M P L
E X A M P
E X A M
E X A
E X
E
and what I want it to look like:
Enter a string: EXAMPLE
E X A M P L E
E X A M P L
E X A M P
E X A M
E X A
E X
E
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
char string[100];
int c, k, length;
printf("Enter a string: ");
gets(string);
length = strlen(string);
printf("\n");
for(c=length; c>0; c--)
{
for(k=0; k<c; k++)
{
printf("%c ", string[k]);
}
printf("\n");
}
getch();
}

You just to add length - c spaces before printing each lines because the less characters you have to print, the more spaces you have to insert:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int c, k, length;
printf("Enter a string: ");
gets(string);
length = strlen(string);
printf("\n");
for(c=length; c>0; c--)
{
//Add some spaces
for(k=0; k < length - c ; k++)
{
printf(" ");
}
for(k=0; k<c; k++)
{
printf("%c ", string[k]);
}
printf("\n");
}
return 0;
}
Example with SAMPLE STRING:
Enter a string: SAMPLE STRING
S A M P L E S T R I N G
S A M P L E S T R I N
S A M P L E S T R I
S A M P L E S T R
S A M P L E S T
S A M P L E S
S A M P L E
S A M P L E
S A M P L
S A M P
S A M
S A
S

Just insert an increasing amount of spaces at every turn (i.e. printf space k times).

Related

how to make a abc pyrmid

i wrote a code and i dont know how to continue from here .. i want to build an abc pyramide from start to back (a ,aba,abcba..etc) for example
a
a b a
a b c b a
a b c d c b a
etc..
this is my code , thanks :)
void aba(int lines)
{
//int i = 97;
char a = 97;
for (int i = 97;i <= lines + 97;i++)
{
printf("%c",i);
for (int j = 97;j <= lines + 97;j++)
{
if (j == i)
break;
printf("%c%c", j,i);
}
printf("\n");
}
void main()
{
aba(3);
}
If you have problems solving a given task always try to split it into smaller jobs:
Start by printing an a for every line of your pyramid:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
printf("%c\n", a);
}
}
Now you want to have a pyramid with one character in the first line, 3 in the second, 5 in the third and so on. You can produce this sequence using (i * 2) + 1:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < (i * 2) + 1 ; j++) {
printf("%c", a);
}
printf("\n");
}
}
The last step would be to increase the character in the first half of the line and decrease it in the last half:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
char a = 'a';
for (int j = 0; j < (i * 2) + 1 ; j++) {
printf("%c", a);
if (j <= i - 1)
a += 1;
else
a -= 1;
}
printf("\n");
}
}
As it is homework, I give you a hint, not the solution:
You should observe the pattern: All lines start with a.
When you numerate the lines from top to bottom starting with 0, the line 0 has an a and 0 additional characters.
line 1 starts with the a and has 1 more upcounting character (b) and then 1 downcounting character (a).
line 2 starts with the a and has 2 more upcounting character (b c) and then 2 downcounting character (b a).
...
So, line i starts with the a and has i more upcounting characters (b c d ....) and then i downcounting characters (... c b a).
Now you have to translate that into code.
void aba(int n)
{
for (int i = 0; i < n; i++)
{
//print here what all lines have in common
for (int j = 1; j <= i; j++)
{
//print the upcounting characters
}
for (int j = 1; j <= i; j++)
{
//print the downcounting characters
}
}
}
For starters pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
It is not necessary that lower case letters follow each other without gaps. For example this in not correct for the EBCDIC table.
Here is a demonstrative program that shows how the required output can be obtained.
#include <stdio.h>
int main(void)
{
const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const size_t N = sizeof( alphabet ) - 1;
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number not greater than %zu (0 - exit ): ", N );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
n %= N + 1;
putchar( '\n' );
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
do { printf( "%c ", *p++ ); } while ( p != alphabet + i + 1 );
if ( --p != alphabet )
{
do { printf( "%c ", *--p ); } while ( p != alphabet );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number not greater than 26 (0 - exit ): 26
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
a b c d e f e d c b a
a b c d e f g f e d c b a
a b c d e f g h g f e d c b a
a b c d e f g h i h g f e d c b a
a b c d e f g h i j i h g f e d c b a
a b c d e f g h i j k j i h g f e d c b a
a b c d e f g h i j k l k j i h g f e d c b a
a b c d e f g h i j k l m l k j i h g f e d c b a
a b c d e f g h i j k l m n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x y x w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x y z y x w v u t s r q p o n m l k j i h g f e d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 10
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
a b c d e f e d c b a
a b c d e f g f e d c b a
a b c d e f g h g f e d c b a
a b c d e f g h i h g f e d c b a
a b c d e f g h i j i h g f e d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number not greater than 26 (0 - exit ): 2
a
a b a
Enter a non-negative number not greater than 26 (0 - exit ): 1
a
Enter a non-negative number not greater than 26 (0 - exit ): 0
The part of the program that outputs the pattern can be placed in a separate function such a way that the pattern can be outputted in any file.
Here you are.
#include <stdio.h>
FILE * display_pattern( size_t n, FILE *fp )
{
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
static const size_t N = sizeof( alphabet ) - 1;
n %= N + 1;
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
do { fprintf( fp, "%c ", *p++ ); } while ( p != alphabet + i + 1 );
if ( --p != alphabet )
{
do { fprintf( fp, "%c ", *--p ); } while ( p != alphabet );
}
fputc( '\n', fp );
}
return fp;
}
int main(void)
{
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number (0 - exit ): " );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar( '\n' );
display_pattern( n, stdout );
putchar( '\n' );
}
return 0;
}
Again the program output might look like
Enter a non-negative number (0 - exit ): 5
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
Enter a non-negative number (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number (0 - exit ): 2
a
a b a
Enter a non-negative number (0 - exit ): 1
a
Enter a non-negative number (0 - exit ): 0
If actually you want to output indeed a pyramid then the function can look as it is shown in the next demonstrative program.
#include <stdio.h>
FILE * display_pattern( size_t n, FILE *fp )
{
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
static const size_t N = sizeof( alphabet ) - 1;
n %= N + 1;
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
fprintf( fp, "%*c ", ( int )( 2 * ( n - i) - 1 ), *p++ );
while ( p != alphabet + i + 1 ) fprintf( fp, "%c ", *p++ );
if ( --p != alphabet )
{
do { fprintf( fp, "%c ", *--p ); } while ( p != alphabet );
}
fputc( '\n', fp );
}
return fp;
}
int main(void)
{
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number (0 - exit ): " );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar( '\n' );
display_pattern( n, stdout );
putchar( '\n' );
}
return 0;
}
Now the program output might look like
Enter a non-negative number (0 - exit ): 5
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
Enter a non-negative number (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number (0 - exit ): 2
a
a b a
Enter a non-negative number (0 - exit ): 1
a
Enter a non-negative number (0 - exit ): 0

Why isn't my printf() statement in my searchPuzzle function isn't working?

For some reason, my print statement within my searchPuzzle function isn't working. Can you guys explain the reason why? I am trying to find certain words within a crossword puzzle which is 15x15. The word I am trying to find is the states with the US, like NewYork for example. The char ** arr represents the crossword puzzle. while the char** list represents the list of states. My go is for my function is to try to find the states in the crossword puzzle and to print out the states it does find. Int listsize has the value of 50. While n has the value of 15.
This is the cross word puzzle:
W D B M J Q D B C J N Q P T I
I R Z U X U Z E A O I O R T N
M N Z P L R N H L Y L X H M D
M Y E K A I D P I U L Y O W I
A O A B A R K U F V I H L A A
L O N M R X K I O J N A V R N
A E P T A A R A R T O W A I A
S U C Z A U S I N A I A L Z V
K O T A O N R K I S S I A O N
A H X S V K A I A E A I B N E
U D S X N X C C D W G S A A V
O I S D W L E J N J T X M H A
M O X W T N H Q D X O Q A Q D
R U U V G E O R G I A Q V D A
V F L O R I D A L G L W O X N
This is the list of states:
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
NewHampshire
NewJersey
NewMexico
NewYork
NorthCarolina
NorthDakota
Ohio
Oklahoma
Oregon
Pennsylvania
RhodeIsland
SouthCarolina
SouthDakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
WestVirginia
Wisconsin
Wyoming
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// DO NOT INCLUDE OTHER LIBRARY!
// Declarations of the two functions you will implement
// Feel free to declare any helper functions
void printPuzzle(char** arr, int n);
void searchPuzzle(char** arr, int n, char** list, int listSize);
// Main function, DO NOT MODIFY!!!
int main(int argc, char **argv) {
int bSize = 15;
if (argc != 2) {
fprintf(stderr, "Usage: %s <puzzle file name>\n", argv[0]);
return 2;
}
int i, j;
FILE *fptr;
char **block = (char**)malloc(bSize * sizeof(char*));
char **words = (char**)malloc(50 * sizeof(char*));
// Open file for reading puzzle
fptr = fopen(argv[1], "r");
if (fptr == NULL) {
printf("Cannot Open Puzzle File!\n");
return 0;
}
// Read puzzle block into 2D arrays
for(i=0; i<bSize; i++){
*(block+i) = (char*)malloc(bSize * sizeof(char));
fscanf(fptr, "%c %c %c %c %c %c %c %c %c %c %c %c %c %c %c\n", *(block+i), *(block+i)+1, *(block+i)+2, *(block+i)+3, *(block+i)+4, *(block+i)+5, *(block+i)+6, *(block+i)+7, *(block+i)+8, *(block+i)+9, *(block+i)+10, *(block+i)+11, *(block+i)+12, *(block+i)+13, *(block+i)+14 );
}
fclose(fptr);
// Open file for reading word list
fptr = fopen("states.txt", "r");
if (fptr == NULL) {
printf("Cannot Open Words File!\n");
return 0;
}
// Save words into arrays
for(i=0; i<50; i++){
*(words+i) = (char*)malloc(20 * sizeof(char));
fgets(*(words+i), 20, fptr);
}
// Remove newline characters from each word (except for the last word)
for(i=0; i<49; i++){
*(*(words+i) + strlen(*(words+i))-2) = '\0';
}
// Print out word list
printf("Printing list of words:\n");
for(i=0; i<50; i++){
printf("%s\n", *(words + i));
}
printf("\n");
// Print out original puzzle grid
printf("Printing puzzle before search:\n");
printPuzzle(block, bSize);
printf("\n");
// Call searchPuzzle to find all words in the puzzle
searchPuzzle(block, bSize, words, 50);
printf("\n");
// Print out final puzzle grid with found words in lower case
printf("Printing puzzle after search:\n");
printPuzzle(block, bSize);
printf("\n");
return 0;
}
void printPuzzle(char** arr, int n){
// This function will print out the complete puzzle grid (arr). It must produce the output in the SAME format as the samples in the instructions.
// Your implementation here
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
printf("%c ", *(*(arr + i) + j));
}
printf("\n");
}
}
void searchPuzzle(char** arr, int n, char** list, int listSize){
// This function checks if arr contains words from list. If a word appears in arr, it will print out that word and then convert that word entry in arr into lower case.
// Your implementation here
for(int e = 0; e < listSize; e++){
for(int f = 0; f < strlen(*(list+e)); f++){
if(*(*(list + e) + f) >= 'a' && *(*(list + e) + f) <= 'z' ){
*(*(list + e) + f) = *(*(list + e) + f) - ('a' - 'A');
}
}
}
int k = 0;
for(int a = 0; a < listSize; a++){
for(int b = 0; b < n; b++){
for(int c = 0; c < n; c++){
if(*(*(list + a) + k) >= 'a' && *(*(list + a) + k) <= 'z' ){
*(*(list + a) + k) = *(*(list + a) + k) - ('a' - 'A');
}
if( *(*(list + a) + k) == *(*(arr + c) + b) ){
k++;
}
if( *(*(list + a) + k) != *(*(arr + c) + b) ){
k = 0;
break;
}
printf("%i ", k);
if ( k == (strlen(*(list+a))-1) ){
printf("Found: ");
for(int l = 0; l < strlen(*(list+a)); l++){
printf("%c", *(*(list + a) + l));
//printf("\n");
}
printf("\n");
k = 0;
break;
}
}
}
}
}
if( *(*(list + a) + k) == *(*(arr + c) + b) ){
k++;
}
if( *(*(list + a) + k) != *(*(arr + c) + b) ){
k = 0;
break;
}
In the first if, you increment k if you find a match. Then, in the next if, we are checking the next character in the word (since we did k++), with the same character *(*(arr + c) + b) from the crossword. For example, in NEWYORK, you match N with N (so far good), then compare E with N which is not equal, so it breaks out of loop. You should use an if .. else here, instead of two separate ifs, since the second condition should only be checked if the first is false.
When you find a non-matching character, you are using break. This will break out of the c loop, meaning that, if any character in a crossword line fails to match the word from list, the remaining characters in that line will not be checked. Here, you don't have to break out of the loop; setting k = 0 should be enough.
In *(*(arr + c) + b) you are incrementing c in the inner loop, so you are only checking for vertical matches in the crossword. If you want to check for horizontal matches also, you should also do the same checks after changing the nesting order of b and c loops. (OR you can check *(*(arr + b) + c)(changed b and c position) in the same loop and use another variable for horizontal in place of k. But note that this does not work if crossword is not square ie. not NxN)
As #bruno mentioned in comments, use arr[c][b] instead of *(*(arr + c) + b) as it is more readable and maintainable. Also use a loop to read characters in the crossword. That will be more maintainable than %c %c %c ...
In my linux machine, the following code is truncating one extra character from the words in list. Most likely because you are on Windows, and Windows uses \r\n line endings and Linux uses \n endings. So this won't work as you expect if your word list file was written in non-windows machine (Mac, Linux). If you want it to work anywhere, you can use strcspn function with \r\n to remove new line characters.
// Remove newline characters from each word (except for the last word)
for(i=0; i<49; i++){
*(*(words+i) + strlen(*(words+i))-2) = '\0';
}
After making changes, you should get this (tell if anything is missing):
Found:ALABAMA
Found:ALASKA
Found:ARIZONA
Found:CALIFORNIA
Found:FLORIDA
Found:GEORGIA
Found:HAWAII
Found:ILLINOIS
Found:INDIANA
Found:NEVADA
Since it is a school work, I will let you make the changes in code.
I modified the print function a bit. I suppose it should work:
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE(X) sizeof(X) / sizeof(X[0])
void printPuzzle(const char ** arrP, int size){
for (int i = 0; i < size; i++){
printf(*arrP++);
printf("\n");
}
}
// Main function, DO NOT MODIFY!!!
int main(int argc, char **argv) {
const char * puzzle [] = {"ABC","DEF","GHI"};
printPuzzle(puzzle, ARRAY_SIZE(puzzle));
return 0;
}

Searching for a substring in 2d array in C

This is something for searching a substring In a 2d array
int left_to_rigth(char matrix[ROW][COLUNM], char str1[])
{
int i = 0, j, counting = 0, wordcnt;
int length = computeLength(str1); //returns legth of string
int index = -1;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COLUNM; j += 1)
{
if (matrix[i][j] == str1[0])
{
for (wordcnt = 0; wordcnt < length; wordcnt++)
{
if (matrix[i][j + wordcnt] == str1[wordcnt])
{
counting++;
}
}
if (counting == length)
{
index = (i *12) + j;
}
}
}
}
return index;
}
The output:
Enter the string to be searched in the puzzle:
SHOUT
position in the puzzle: 12
PUZZLE(MATRIX)
X T Z M Q Y K C E C F H -->0 1 2 3 4 5 6 7 8 9 10 11
*S H O U T* E X O E A P I -->12 13 14 ------------23
X G T L Q B E L T N F K
A I R I D Z A L L I O D
M E I E T Y S E H R T I
A W B R N E T C W O H X
N O U I R U Z T S C C T
U D T P E C J I E H R U
A L E M C S Y O N I U R
L V *K E R E M* N I P H E
E A N B U R E J O N C Y
A W I I I J N J R U Y F
D W T N T H E N P J Y T
E Q L Z D I L E M M A B
R C I T E N G A M T P C
So the function returns the starting point of SHOUT which is 12 but when I try to search for the word KEREM it should give me 110 but instead it return -1 which says that the word doesnt exist.
It seems like the code only searches for the first 3 lines every input I enter after that returns -1. Could you please help I am a beginner
This is just the first part I need to make it so that it searches in every direction I can either write 4 seperate functions and call them if they dont return -1 but I need to get this working first
Okay, I've done a few speedups and simplifications.
No need for a separate counting [for left-to-right and right-to-left, at least] as you can use wordidx
Also, once you find a match on the inner loop, there is no need to continue with it. And, you can stop the outer loop early
It's faster to calculate the length of str1 outside of the call and pass length as an argument. Also, strlen should work just fine.
On left-to-right, there is no need for j to go all the way to COLUMN - 1 as the last N slots can not match if there isn't enough room on the matrix line to fulfill the remaining string length.
Also, it's undefined behavior because you'll spill over into the next row. This would be harmless [but wrong result] except for the last row, where you'll go beyond the end of the entire matrix.
So, I added a jmax value of COLUMN - length
The right-to-left is slightly trickier. The jmax trick is critical.
So, here are the two functions [they compile cleanly, but I've not tested them]:
#include <string.h>
#define ROW 10
#define COLUMN 10
int
left_to_right(char matrix[ROW][COLUMN], const char *str1, int length)
{
char *matcur;
int i;
int j;
int wordidx;
int jmax = COLUMN - length;
int index = -1;
jmax += 1;
for (i = 0; i < ROW; ++i) {
for (j = 0; j < jmax; ++j, ++matcur) {
matcur = &matrix[i][0];
if (matcur[0] != str1[0])
continue;
for (wordidx = 1; wordidx < length; ++wordidx) {
if (matcur[wordidx] != str1[wordidx])
break;
}
if (wordidx == length) {
index = (i * COLUMN) + j;
break;
}
}
if (index >= 0)
break;
}
return index;
}
int
right_to_left(char matrix[ROW][COLUMN], const char *str1, int length)
{
const char *matcur;
int i;
int j;
int wordidx;
int jmax = COLUMN - length;
int index = -1;
for (i = 0; i < ROW; ++i) {
matcur = &matrix[i][jmax];
for (j = jmax; j >= 0; --j, --matcur) {
if (matcur[0] != str1[0])
continue;
for (wordidx = 0; wordidx < length; ++wordidx) {
if (matcur[wordidx] != str1[wordidx])
break;
}
if (wordidx == length) {
index = (i * COLUMN) + j;
break;
}
}
if (index >= 0)
break;
}
return index;
}

Program for this Alphabet pattern in c++

Is there any other way to do this program with less number of loops.Its not much efficient
#include <iostream>
using namespace std;
int main() {
int i,j,n,s;
cout<<"Enter the value of n";
cin>>n;
for(i=1;i<=n;i++){
for(s=1;s<=n-i;s++){
cout<<" ";
}
char ch=97;
int k=1;
for(j=1;j<=(i*2-1);j++) {
if (k%2!= 0){
cout <<ch;
ch++;
} else {
cout<<" ";
}
k++;
}
cout<<endl;
}
}
output:
Enter the value of n6
a
a b
a b c
a b c d
a b c d e
a b c d e f
Try the following code-
#include<stdio.h>
main()
{
int i,j,k,num;
printf("Enter the number of letter \n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
for(j=num-1;j>i;j--)
printf(" ");
for(k=0;k<=i;k++)
printf("%c ",(97+k));
printf("\n");
}
}
Sample input and output-
sathish#ubuntu:~/c/basics$ ./a.out
Enter the number of letter
4
a
a b
a b c
a b c d
#include <stdio.h>
int main(){
char *pat = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
int i, n;
printf("input n : ");
scanf("%d", &n);
for(i = 1;i<=n;++i)
printf("%*s%.*s\n", n - i, "", (i << 1) - 1, pat);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cout << "Enter the value of n : ";
cin >> n;
string spaces(n, ' ');
string pat("a b c d e f g h i j k l m n o p q r s t u v w x y z");
for(int i=1;i<=n;i++){
cout << spaces.substr(i);
cout << pat.substr(0, (i << 1) -1);
cout << endl;
}
}

fgets is reading in too late

Okay. After having completely rewritten this program over in favor of fgets, it mostly reads in the words.
This comes in two pieces, compiled upon a gcc linux machine. However, a redirect statement is required for this.
So once compiled it must be run like this:
./a.out < data1
So here's "data1":
S T E L B M T F E Y D E E P S R T C I A E E
N N E L I T R L B D E T A R E M U N E T Y L
N O I T A N I M I R C N I F L E S S E N T A
A U I D E W A R R A N T N U P R U S S E R P
P G S G E A L P A P B A N P S A S S N M E A
C O N S I T U T I O N D E E C W S O O H P D
S V W D E L A N E E J A M E S M A D I S O N
A E D E S N E G R J C U L T N O H L T I R A
A R C E R R T R E E S B O N E E I D N N P R
S N J U D I C I A L A S S E C O R P E U D I
S M R A R A E B W B E S S M E O A U V P E M
O E O I A I L N O U C D O D S S E N N I G R
L N I D G Y T R C O M P E N S A T I O N N D
D T O Z E H P Y N D R L E E A O H S C O I B
I T P S U E T G O L U Z M M R B E H P I R T
E O I E A R R S U U I B H A Y L L M S T F A
R I N R E E E F U T L V Q U A R T E R I N G
S I D B S R R D I Y E N I G M I A N A T I R
S Q I S E B S C N S P E E C H R O T A E Y N
D L C M I L I T I A F L R N C A T S S P S E
R U T E D Y L E B I L C O H M L E T E S Y Y
L S T R T E W Z L I O S A E N S A E I Y A L
AMENDMENT
ASSEMBLY
BAIL
BEARARMS
CITIZEN
CIVIL
COMPENSATION
CONGRESS
CONSITUTION
CONVENTIONS
DELEGATED
DOUBLEJEOPARDY
DUEPROCESS
ENUMERATED
FREEDOM
GOVERNMENT
ILLEGAL
INDICT
INFRINGED
JAMESMADISON
JUDICIAL
LAWSUIT
LIBEL
LIBERTY
LIFE
MILITIA
MIRANDA
NECESSARY
PEACEABLY
PEERS
PETITION
POWER
PRESS
PROBABLECAUSE
PROPERTY
PUNISHMENTS
QUARTERING
RELIGION
RIGHTS
SEARCH
SECURITY
SEIZURE
SELFINCRIMINATION
SLANDER
SOLDIERS
SPEECH
SPEEDY
TRIAL
UNREASONABLE
WARRANT
WITNESS
Here's the program itself:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 50
#define COLUMNS 50
#define TR 100
#define TC 100
int main( )
{
int s1 = 0, s2 = 0;
int sizeOfGrid = 0;
int wordCount = 0;
int rowNumber = 0;
int colNumber = 0;
/* */
char tempLetters[ROWS][COLUMNS];
char letters[ROWS][COLUMNS];
char words[ROWS][COLUMNS];
char wordTemp[50];
char firstRow[100], nextRow[100];
/* fgets(stdin); */
char firstRowTemp[100], nextRowTemp[100];
/* output input */
setbuf(stdout, NULL);
for (s2 = 0; s2 < 100; s2++)
{
firstRowTemp[s2] = ' ';
nextRowTemp[s2] = ' ';
if (s2 < 50)
{
wordTemp[s2] = ' ';
for (s1 = 0; s1 < 50; s1++)
{
words[s2][s1] = ' ';
}
}
}
/* Let's attempt to despace the first line, and then count the chars. */
fgets(firstRow,100,stdin);
s1 = 0;
s2 = 0;
for (colNumber = 0; colNumber < strlen(firstRow); colNumber++)
{
if ((firstRow[colNumber] != ' ') && (firstRow[colNumber] != '\n'))
{
firstRowTemp[s1] = firstRow[colNumber];
letters[rowNumber][s2++] = firstRowTemp[s1++];
sizeOfGrid++;
}
}
/* We have now successfully gotten the size of the grid, so lets
* put it to good use within our next loops to read in the rest
* of the lines.
* We take it in a for loop up to sizeOfGrid*2 because right now,
* we still have spaces. Once we get rid of those, it'll be able to utilize
* normal sizeOfGrid count.*/
for (rowNumber = 1; rowNumber < sizeOfGrid*2; rowNumber++)
{
fgets(nextRow, 100, stdin);
s1 = 0;
s2 = 0;
for (colNumber = 0; colNumber < sizeOfGrid*2; colNumber++)
{
if ((nextRow[colNumber] != ' ') && (tempLetters[rowNumber][colNumber] != '\n'))
{
nextRowTemp[s1] = nextRow[colNumber];
letters[rowNumber][s2++] = nextRowTemp[s1++];
}
}
}
/* Next up, it's time to store the words. Scan the rest of the file for words
* and store them as chars. */
rowNumber = 0;
colNumber = 0;
while(fgets(wordTemp,50,stdin) != NULL)
{
for (s1 = 0; s1 < strlen(wordTemp); s1++)
{
if (wordTemp[s1] != '\n')
{
words[rowNumber][colNumber++] = wordTemp[s1];
}
}
colNumber = 0;
wordCount++;
rowNumber++;
}
/* For testing purposes and making sure it receives the grid entirely.*/
for (s2 = 0; s2 < sizeOfGrid; s2++)
{
printf("%c",firstRowTemp[s2]);
}
printf("\nSize of grid is %d\n",sizeOfGrid);
printf("\n");
for (rowNumber = 0; rowNumber < sizeOfGrid; rowNumber++)
{
for (colNumber = 0; colNumber < sizeOfGrid; colNumber++)
{
printf("%c", letters[rowNumber][colNumber]);
}
printf("\n");
}
for (rowNumber = 0; rowNumber < ROWS; rowNumber++)
{
for (colNumber = 0; colNumber < COLUMNS; colNumber++)
{
if ((words[rowNumber][colNumber] != ' ') && (words[rowNumber][colNumber] != '\n'))
printf("%c", words[rowNumber][colNumber]);
else
break;
}
if (colNumber > 1)
printf("\n");
}
/* End print debugging here.*/
return 0;
}
And now for my question itself...
It appears fgets is skipping over a large number of words, starting only at LIBEL instead of running through the top of the list (AMENDMENTS in this case). Where is it going wrong?
In the grid you've shown us, there are spaces between letters horizontally, but no blank lines between the lines of letters, so you need to use sizeOfGrid*2 to loop over the columns, but not the rows.

Resources