I want to extract only numbers from a string, and to put them in an array.
For example, string is "fds34 21k34 k25j 6 10j340ii0i5".
I want to make one array, which elements are like following:
arr[0]=34, arr[1]=21, arr[2]=34, arr[3]=25, arr[4]=6, arr[5]=10, arr[6]=340, arr[7]=0, arr[8]=5;
my trial code:
#include <stdio.h>
int main()
{
char ch;
int i, j;
int pr[100];
i=0;
while ( (ch = getchar()) != '\n' ){
if( ch>='0' && ch<='9' ){
pr[i] = ch-'0';
i++;
}
for(j=0; j<i; j++)
printf("pr[%d]: %d\n", j, pr[j]);
return 0;
}
My code cannot recognize the contiguous number. just 'pr' array has {3, 4, 2, 1, 3, 4, 2, 5, 6, 1, 0, 3, 4, 0, 0, 5}. Is there any method to implement my objective?
That is algorithm:
Use a string to store current number. At first, init it as empty string
when ch is a digit('0'..'9'), put it in this string
when ch is not a digit, if string is not empty, convert current string to number by atoi function, and store that number in array. After that, init current string to empty again.
Ex: i have string "ab34 56d1"
use string str to store current number, at first str =""(empty)
ch = 'a', do nothing (because current string is empty)
ch = 'b', do nothing
ch = '3', put it to string, so str = "3"
ch = '4', put it to str, now str = "34"
ch = ' ', convert "34" to 34, save it in array, init str="" again
.....
Create a state machine.
Keep track of the previous character - was it a digit?
When a digit is detected ...
... If continuing a digit sequence, *10 and add
... Else start new sequence
Do not overfill pr[]
Use int ch to properly detect EOF
//char ch;
int ch;
bool previous_digit = false;
int pr[100];
int i = 0 - 1;
while (i < 100 && (ch = getchar()) != '\n' && ch != EOF) {
if (ch>='0' && ch<='9') {
if (previous_digit) {
pr[i] = pr[i] * 10 + ch - '0';
} else {
i++;
pr[i] = ch - '0';
}
previous_digit = true;
} else {
previous_digit = false;
}
}
i++;
Use scanf. Life becomes simpler when you use standard functions instead of making up your own algorithms.
This code uses scan read a line of user input and then parses it. Detected digits are put into an array and the search index is shifted forward by the number of digits.
char line[100];
int p[100];
int readNums = 0;
int readDigits = 0;
int len;
int index = 0;
//get line
scanf("%99[^\n]%n",line,&len);
while( index < len ){
if(line[index] <= '9' && line[index] >= '0'){
if(sscanf(line + index, "%d%n", p + readNums, &readDigits) != 1)
fprintf(stderr, "failed match!!!! D:\n");
index += readDigits;
readNums++;
}
index++;
}
//print results
printf("read %d ints\n", readNums);
for(int i = 0; i < readNums; i++)
printf("p[%d] = %d\n", i, p[i]);
Here is a working code. I try 3-4 times it works fine.
chPrevious will hold the previous state of ch. There is no need to store the digits into the string of digit. We can simply use an integer for this purpose.
#include<stdio.h>
#define NONDIGIT 'a'
int main() {
char ch, chPrevious; //chPrevious hold the previous state of ch.
chPrevious = NONDIGIT;
int temp = 0;
int pr[100];
int i = 0;
while ( (ch = getchar()) != '\n' ){
if( (ch>='0' && ch<='9') && (chPrevious>='0' && chPrevious<= '9')){
temp = temp * 10 + (ch - '0');
} else if (ch>= '0' && ch<= '9' && temp != 0) {
pr[i++] = temp;
temp = 0;
temp = ch - '0';
} else if (ch >= '0' && ch <= '9') {
temp = ch-'0';
}
chPrevious = ch;
}
pr[i++] = temp;
for(int j=0; j<i; j++)
printf("pr[%d]: %d\n", j, pr[j]);
return 0;
}
There may be other way too do to this and efficient also. Please ignore the bad styling. You should also improve this code as well.
Related
Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.
The algorithm I decided to follow for this was as follows:
If length of input line < maxcol (the column after which one would have to fold), then print the line as it is.
If not, from maxcol, I check towards it's left, and it's right to find the closest non-space character, and save them as 'first' and 'last'. I then print the character array from line[0] to line[first] and then the rest of the array, from line[last] to line[len] becomes the new line array.
Here's my code:
#include <stdio.h>
#define MAXCOL 5
int getline1(char line[]);
int main()
{
char line[1000];
int len, i, j, first, last;
len = getline1(line);
while (len > 0) {
if (len < MAXCOL) {
printf("%s\n", line);
break;
}
else {
for (i = MAXCOL - 1; i >= 0; i--) {
if (line[i] != ' ') {
first = i;
break;
}
}
for (j = MAXCOL - 1; j <= len; j++) {
if (line[j] != ' ') {
last = j;
break;
}
}
//printf("first %d last %d\n", first, last);
for (i = 0; i <= first; i++)
putchar(line[i]);
putchar('\n');
for (i = 0; i < len - last; i++) {
line[i] = line[last + i];
}
len -= last;
first = last = 0;
}
}
return 0;
}
int getline1(char line[])
{
int c, i = 0;
while ((c = getchar()) != EOF && c != '\n')
line[i++] = c;
if (c == '\n')
line[i++] = '\n';
line[i] = '\0';
return i;
}
Here are the problems:
It does not do something intelligent with very long lines (this is fine, as I can add it as an edge case).
It does not do anything for tabs.
I cannot understand a part of the output.
For example, with the input:
asd de def deffff
I get the output:
asd
de
def
defff //Expected until here
//Unexpected lines below
ff
fff
deffff
deffff
deffff
Question 1 - Why do the unexpected lines print? How do I make my program/algorithm better?
Eventually, after spending quite some time with this question, I gave up and decided to check the clc-wiki for solutions. Every program here did NOT work, save one (The others didn't work because they did not cover certain edge cases). The one that worked was the largest one, and it did not make any sense to me. It did not have any comments, and neither could I properly understand the variable names, and what they represented. But it was the ONLY program in the wiki that worked.
#include <stdio.h>
#define YES 1
#define NO 0
int main(void)
{
int TCOL = 8, ch, co[3], i, COL = 19, tabs[COL - 1];
char bls[COL - 1], bonly = YES;
co[0] = co[1] = co[2] = 0;
while ((ch = getchar()) != EOF)
{
if (ch != '\t') {
++co[0];
++co[2];
}
else {
co[0] = co[0] + (TCOL * (1 + (co[2] / TCOL)) - co[2]);
i = co[2];
co[2] = TCOL + (co[2] / TCOL) * TCOL;
}
if (ch != '\n' && ch != ' ' && ch != '\t')
{
if (co[0] >= COL) {
putchar('\n');
co[0] = 1;
co[1] = 0;
}
else
for (i = co[1]; co[1] > 0; --co[1])
{
if (bls[i - co[1]] == ' ')
putchar(bls[i - co[1]]);
else
for (; tabs[i - co[1]] != 0;)
if (tabs[i - co[1]] > 0) {
putchar(' ');
--tabs[i - co[1]];
}
else {
tabs[i - co[1]] = 0;
putchar(bls[i - co[1]]);
}
}
putchar(ch);
if (bonly == YES)
bonly = NO;
}
else if (ch != '\n')
{
if (co[0] >= COL)
{
if (bonly == NO) {
putchar('\n');
bonly = YES;
}
co[0] = co[1] = 0;
}
else if (bonly == NO) {
bls[co[1]] = ch;
if (ch == '\t') {
if (TCOL * (1 + ((co[0] - (co[2] - i)) / TCOL)) -
(co[0] - (co[2] - i)) == co[2] - i)
tabs[co[1]] = -1;
else
tabs[co[1]] = co[2] - i;
}
++co[1];
}
else
co[0] = co[1] = 0;
}
else {
putchar(ch);
if (bonly == NO)
bonly = YES;
co[0] = co[1] = co[2] = 0;
}
}
return 0;
}
Question 2 - Can you help me make sense of this code and how it works?
It fixes all the problems with my solution, and also works by reading character to character, and therefore seems more efficient.
Question 1 - Why do the unexpected lines print? How do I make my program/algorithm better?
You are getting the unexpected lines in the output because after printing the array, you are not terminating the new line array with null character \0 -
Here you are copying character from starting from last till len - last, creating a new line array:
for (i = 0; i < len - last; i++) {
line[i] = line[last + i];
}
You have copied the characters but the null terminating character is still at its original position. Assume the input string is:
asd de def deffff
So, initially the content of line array will be:
"asd de def deffff\n"
^
|
null character is here
Now after printing asd, you are copying characters from last index of line till len - last index to line array itself starting from 0 index. So, after copying the content of line array will be:
"de def deffff\n deffff\n"
|____ _____|
\/
This is causing the unexpected output
(null character is still at the previous location)
So, after for loop you should add the null character just after the last character copied, like this:
line [len - last] = '\0';
With this the content of line array that will be processed in the next iteration of while loop will be:
"de def deffff\n"
One more thing, in the line array you can see the \n (newline) character at the end. May you want to remove it before processing the input, you can do:
line[strcspn(line, "\n")] = 0;
Improvements that you can do in your program:
1. One very obvious improvement that you can do is to use pointer to the input string while processing it. With the help of pointer you don't need to copy the rest of the array, apart from processed part, again to the same array till the program process the whole input. Initialize the pointer to the start of the input string and in every iteration just move the pointer to appropriate location and start processing from that location where pointer is pointing to.
2. Since you are taking the whole input first in a buffer and then processing it. You may consider fgets() for taking input. It will give better control over the input from user.
3. Add a check for line array overflow, in case of very long input. With fgets() you can specify the maximum number of character to be copied to line array from input stream.
Question 2 - Can you help me make sense of this code and how it works?
The program is very simple, try to understand it at least once by yourself. Either use a debugger or take a pen and paper, dry run it once for small size input and check the output. Increase the input size and add some variations like multiple space characters and check the program code path and output. This way you can understand it very easily.
Here's another (and I think better) solution to this exercise :
#include <stdio.h>
#define MAXCOL 10
void my_flush(char buf[]);
int main()
{
int c, prev_char, i, j, ctr, spaceleft, first_non_space_buf;
char buf[MAXCOL+2];
prev_char = -1;
i = first_non_space_buf = ctr = 0;
spaceleft = MAXCOL;
printf("Just keep typing once the output has been printed");
while ((c = getchar()) != EOF) {
if (buf[0] == '\n') {
i = 0;
my_flush(buf);
}
//printf("Prev char = %c and Current char = %c and i = %d and fnsb = %d and spaceleft = %d and j = %d and buf = %s \n", prev_char, c, i, first_non_space_buf, spaceleft, j, buf);
if ((((prev_char != ' ') && (prev_char != '\t') && (prev_char != '\n')) &&
((c == ' ') || (c == '\t') || (c == '\n'))) ||
(i == MAXCOL)) {
if (i <= spaceleft) {
printf("%s", buf);
spaceleft -= i;
}
else {
putchar('\n');
spaceleft = MAXCOL;
for (j = first_non_space_buf; buf[j] != '\0'; ++j) {
putchar(buf[j]);
++ctr;
}
spaceleft -= ctr;
}
i = 0;
my_flush(buf);
buf[i++] = c;
first_non_space_buf = j = ctr = 0;
}
else {
if (((prev_char == ' ') || (prev_char == '\t') || (prev_char == '\n')) &&
((c != ' ') && (c != '\t') && (c != '\n'))) {
first_non_space_buf = i;
}
buf[i++] = c;
buf[i] = '\0';
}
prev_char = c;
}
printf("%s", buf);
return 0;
}
void my_flush(char buf[])
{
int i;
for (i = 0; i < MAXCOL; ++i)
buf[i] = '\0';
}
Below is my solution, I know the thread is no longer active but my code might help someone who's facing issues to grasp the already presented code snippets.
*EDIT
explaination
Keep reading input unless the input contains '\n', '\t' or there've been
atleast MAXCOl chars.
Incase of '\t', use expandTab to replace with required spaces and use printLine if it doesn't exceed MAXCOl.
Incase of '\n', directly use printLine and reset the index.
If index is 10:
find the last blank using findBlank ad get a new index.
use printLine to print the current line.
get new index as 0 or index of newly copied char array using the newIndex function.
code
/* fold long lines after last non-blank char */
#include <stdio.h>
#define MAXCOL 10 /* maximum column of input */
#define TABSIZE 8 /* tab size */
char line[MAXCOL]; /* input line */
int expandTab(int index);
int findBlank(int index);
int newIndex(int index);
void printLine(int index);
void main() {
int c, index;
index = 0;
while((c = getchar()) != EOF) {
line[index] = c; /* store current char */
if (c == '\t')
index = expandTab(index);
else if (c == '\n') {
printLine(index); /* print current input line */
index = 0;
} else if (++index == MAXCOL) {
index = findBlank(index);
printLine(index);
index = newIndex(index);
}
}
}
/* expand tab into blanks */
int expandTab(int index) {
line[index] = ' '; /* tab is atleast one blank */
for (++index; index < MAXCOL && index % TABSIZE != 0; ++index)
line[index] = ' ';
if (index > MAXCOL)
return index;
else {
printLine(index);
return 0;
}
}
/* find last blank position */
int findBlank(int index) {
while( index > 0 && line[index] != ' ')
--index;
if (index == 0)
return MAXCOL;
else
return index - 1;
}
/* re-arrange line with new position */
int newIndex(int index) {
int i, j;
if (index <= 0 || index >= MAXCOL)
return 0;
else {
i = 0;
for (j = index; j < MAXCOL; ++j) {
line[i] = line[j];
++i;
}
return i;
}
}
/* print line until passed index */
void printLine(int index) {
int i;
for(i = 0; i < index; ++i)
putchar(line[i]);
if (index > 0)
putchar('\n');
}
So my program should get input from an user and store it in an array. After that if the input string includes three 'a's in a row it should be replaced with a single '*'. However I can't seem to get it right. It only replaces the first a with a *. I tried to replace the following 2 a with a blank but the output looks funny.
For this exercise I have to use putchar() and getchar().
Thank you in advance.
#include <stdio.h>
char c;
char buffer[256];
int counter= 0;
int i;
int main()
{
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >255) {
break;
}
}
for(i=0; i<256; i++) {
if(buffer[i]== 'a'&&buffer[i+1]=='a'&&buffer[i+2]=='a')
{
buffer[i]= '*';
buffer[i+1]=' ';
buffer[i+2]=' ';
}
putchar(buffer[i]);
}
putchar('\n');
return 0;
}
So my program should get input from an user and store it in an array.
After that if the input string includes three 'a's in a row it should
be replaced with a single '*'. However I can't seem to get it right.
You almost got it! Just move index by 2 to and continue.
#include <stdio.h>
char c;
char buffer[256];
int counter= 0;
int i;
int main(void)
{
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >= 255) {
break;
}
}
buffer[counter] ='\0';
for(i=0; i<256; i++) {
if(buffer[i]== 'a'&&buffer[i+1]=='a'&&buffer[i+2]=='a')
{
buffer[i]= '*';
putchar(buffer[i]);
i = i + 2;
continue;
}
putchar(buffer[i]);
}
putchar('\n');
return 0;
}
Test:
123aaa456aaa78
123*456*78
In string you must assign a end of character at the end and that is call null character \0 or just a numeric 0. Correct your code like below:-
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >=255) {
break;
}
}
buffer[counter] ='\0';// or buffer[counter] =0;
To avoid side effect in a string array always set all its value with 0 first:-
char buffer[256];
memset(buffer, 0, sizeof(buffer));
If you want to change the number of characters, you will need to create a different buffer to copy the output to.
If you really just want to output to the console, you could just write every character until you hit your matching string.
#include <stdio.h>
char c;
char buffer[256];
char output[256];
int counter= 0;
int i, j;
int main()
{
while ((c = getchar()) != '\n') {
buffer[counter] = c;
counter++;
if (counter >255) {
break;
}
}
buffer[counter] = 0;
for(i=0, j=0; i<256; i++, j++) {
if(buffer[i] == 'a' && buffer[i+1] == 'a'&& buffer[i+2] == 'a')
{
output[j]= '*';
i += 2;
}
else
output[j] = buffer[i];
putchar(output[j]);
}
putchar('\n');
return 0;
}
There are multiple problems in your code:
there is no reason to make all these variables global. Declare them locally in the body of the main function.
use int for the type of c as the return value of getchar() does not fit in a char.
you do not check for EOF.
your test for buffer overflow is off by one.
you do not null terminate the string in buffer. You probably make buffer global so it is initialized to all bits 0, but a better solution is to set the null terminator explicitly after the reading loop.
to replace a sequence of 3 characters with a single one, you need to copy the rest of the string.
You can use a simple method referred as the 2 finger approach: you use 2 different index variables into the same array, one for reading, one for writing.
Here is how it works:
#include <stdio.h>
int main() {
char buffer[256];
int c;
size_t i, j, counter;
for (counter = 0; counter < sizeof(buffer) - 1; counter++) {
if ((c = getchar()) == EOF || c == '\n')
break;
buffer[counter] = c;
}
buffer[counter] = '\0';
for (i = j = 0; i < counter; i++, j++) {
if (buffer[i] == 'a' && buffer[i + 1] == 'a' && buffer[i + 2] == 'a') {
buffer[j] = '*';
i += 2;
} else {
buffer[j] = buffer[i];
}
}
buffer[j] = '\0'; /* set the null terminator, the string may be shorter */
printf("modified string: %s\n", buffer);
return 0;
}
I'm trying to read a string in an array, and if a character is not any of the excluded characters int a = ('a'||'e'||'i'||'o'||'u'||'y'||'w'||'h'); it should copy the character into a new array, then print it.
The code reads as:
void letter_remover (char b[])
{
int i;
char c[MAX];
int a = ('a'||'e'||'i'||'o'||'u'||'y'||'w'||'h');
for (i = 0; b[i] != '\0'; i++)
{
if (b[i] != a)
{
c[i] = b[i];
}
i++;
}
c[i] = '\0';
printf("New string without forbidden characters: %s\n", c);
}
However it only prints New string without forbidden characters: h, if the inputted array is, for example hello. I'd like the output of this to be ll (with h, e and o removed).
Use this:
if (b[i] != 'a' && b[i] != 'e' && b[i] != 'i' && b[i] != 'o' && b[i] != 'u' && b[i] != 'y' && b[i] != 'w' && b[i] != 'h')
The boolean OR operator just returns 0 or 1, it doesn't create an object that automatically tests against all the parameters to the operator.
You could also use the strchr() function to search for a character in a string.
char a[] = "aeiouywh";
for (i = 0; b[i] != '\0'; i++)
{
if (!strchr(a, b[i]))
{
c[i] = b[i];
}
i++;
}
c[i] = '\0';
int a = ('a'||'e'||'i'||'o'||'u'||'y'||'w'||'h');
...has an entirely different meaning than you expect. When you Boolean-OR together all those characters, a becomes 1. Since b[] contains no character value 1, no characters will be excluded. Also, your c[] is going to have empty slots if you had tested correctly.
You can use strcspn() to test if your string contains your forbidden characters. For example...
// snip
int i=0, j=0;
char * a = "aeiouywh";
while (b[i])
{
int idx = strcspn(&b[i], a);
if (idx >= 0)
{
if (idx > 0)
strncpy(&c[j], &b[i], idx);
j += idx;
i += idx + 1;
}
}
// etc...
Also, you must be sure c[] is large enough to contain all the characters that might be copied.
Hey I'm really new to programming and having trouble with arrays. Can someone help me with this project. "c programming a modern approach: modify a program that reverses the words of a sentence so that it stores the words in a two dimensional char array as it reads the sentence, with each row of the array storing a single word. assume that the sentence contains no more than 30 words and no word is more than 20 characters long. Be sure to store a null character at the end of each word so that it can be treated as a string"
(also i don't get what its saying about the null character).
here's my try but it's not working. i think i'm close though.
#include <stdio.h>
#define MAX_SENTENCE_LEN 80
#define SENTENCE_MAX 30
#define WORD_MAX 20
int main(void)
{
char ch, sentence[MAX_SENTENCE_LEN] = {' '}, terminator = '.';
int n, i, j, start, finish;
printf("Enter a sentence: ");
for (n = 1; n < MAX_SENTENCE_LEN; n++) {
ch = getchar();
if (ch == '.' || ch == '?' || ch == '!') {
terminator = ch;
break;
}
sentence[n] = ch;
}
printf("Reversal of sentence:");
finish = n;
for (start = finish - 1; start >= 0; start--) {
if (sentence[start] == ' ') {
for (i = start; i < finish; i++)
putchar(sentence[i]);
finish = start;
}
{
int sentence[SENTENCE_MAX][WORD_MAX];
int word[30][20];
for (i=0; i< SENTENCE_MAX;i++){
for (j=0; j<WORD_MAX; j++)
sentence[i][j]=-1;
}
}
}
printf("%c\n", terminator);
return 0;}
i wrote a new code which i think is closer to what i want but it still won't run. do i have a faulty compiler or what?
anyway here's the new code
#include<stdio.h>
#define N 100
int main (void)
{
char sentence[N][N], ch, termChar;
int i = 0, l = 0, count = 0;
int j = 0, k, start, finish, word;
printf("enter a sentence: ");
while (ch = getchar())
{
sentence[i][l++]= ch;
if (ch == ' ')
{
sentence[i][l] = '\0';
i++;
l = 0;
count++;
}
if (ch == '.' || ch == '!' || ch == '?')
{
sentence[i][l-1]= ' ';
sentence[i][l]= '\0';
termChar = ch;
count ++;
break;
}
}
for(i=count ; i>=0; i--)
printf("%s ", sentence[i]);
printf("%c\n", termChar);
return 0;
}
Your code worked perfectly in my environment (Windows, C99 compiler, 32bit build). I entered a short sentence, and it reversed it:
Regarding: i don't get what its saying about the null character
a C string is defined by a null character: \0, at the end of a char array. example char string[]="word" looks like: |w|o|r|d|\0| in memory.
Without the \0, it would simply be a char array, but not a string, and would therefore not be useable in any of the string functions such as strcpy(), strlen(), etc.
By the way, sentence creation and initialization:
char sentence[MAX_SENTENCE_LEN] = {' '};
Does not guarantee contents for the entire length of the char array.
This may be the reason your environment is not running your code, while my environment does.
Depending on compiler, OS, and other random factors, sentence could be filled with anything. So, if your code is not running on your machine, it is likely that you just need to initialize sentence to \0. Replace that line with these:
char sentence[MAX_SENTENCE_LEN]; //create
memset(sentence, 0 ,MAX_SENTENCE_LEN); //zero all memory
sentence[0]=' '; //set first char to a space (' '). (not sure why)
Also by chance, if the user input results in string length == MAX_SENTENCE_LEN, then your program will crash as there is only enough room in sentence for MAX_SENTENCE_LEN-1 + \0.
#include <stdio.h>
#define MAX_SENTENCE_LEN 80
#define SENTENCE_MAX 30
#define WORD_MAX 20
int main(void){
char ch, sentence[MAX_SENTENCE_LEN] = {' '}, terminator = '.';
int n, i, j, start, finish;
char word[SENTENCE_MAX][WORD_MAX+1];
int wc=0, wcc=0;
printf("Enter a sentence: ");
for (n = 1; n < MAX_SENTENCE_LEN; n++) {
ch = getchar();
if (ch == '.' || ch == '?' || ch == '!') {
terminator = ch;
break;
} else if(ch != ' '){
word[wc][wcc++] = ch;
} else if(ch == ' '){//this is assumed to be one space between words.
word[wc++][wcc] = '\0';//null character
wcc = 0;
}
sentence[n] = ch;
}
word[wc++][wcc] = '\0';
printf("Reversal of sentence:");
finish = n;
for (start = finish - 1; start >= 0; start--) {
if (sentence[start] == ' ') {
for (i = start; i < finish; i++)
putchar(sentence[i]);
finish = start;
}
}
printf("%c\n", terminator);
for(i=wc-1;i>=0;--i){
printf("%s", word[i]);
if(i>0)
putchar(' ');
}
printf("%c\n", terminator);
return 0;
}
I am working in C and trying to read a file and save the chars returned by fgetc in an array. The problem is that fgetc is returning a random char repeatedly. Marked location in comment. For example, "wwwwwwwwwwww..." or "############...". Any help is appreciated. Here is the function:
void removeCategories(FILE *category, int *prodPrinted){
char more[16] = { '\0' }, hidden[17] = { '\0' }, temp = '\0', mdn[] = { "More Data Needed" }, hnl[] = { "Hidden non listed" };
int newLineCount = 0, i, ch = '\0';
do{
/*shift char in each list -> one*/
for (i = 16; i > 0; i--){
if (i <= 16){
hidden[i] = hidden[i - 1];
}
if (i <= 15){
more[i] = more[i - 1];
}
}
more[0] = hidden[0] = ch = ( fgetc(category));
printf("%c", &ch); /*problem is here, prints random char repeatedly*/
if (strcmp(more, mdn) == 0 || strcmp(hidden, hnl) == 0){
prodPrinted[newLineCount] = 0;
printf("%c", more[0]); /*test print*/
}
if (ch == '\n'){
newLineCount++;
}
} while (ch != EOF);
}
Issue is in your call to print the character
printf("%c", &ch);
this is actually trying to print the address of your ch on the stack (interpreted as a char).
What you want is:
printf("%c", ch);
which will print the contents of that stack address correctly (as a char)