most popular character on stdin - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int ascii[255]; //starts as empty table, will hold all the character occurences
memset(ascii, 0, sizeof(ascii)); // sets all table values to 0
int c=0;
int i=0;
while (getchar() !=EOF){
c=getchar();
ascii[c]=(ascii[c]+1);
}
for (i=0;i<255;i++){
printf("%d;",ascii[i]);
}
return 0;
}
Hello, ive created the above code to check how many times each character occurs in a .txt file, but im getting really erratic behaviour, the numbers that im getting dont reflect the contents of file at all. Could you tell me where is my error?

You have two getchar() calls, so you are missing one character in each call, change this
while (getchar() != EOF)
to
while ((c = getchar()) != EOF)
and remove the next line
c = getchar();

Related

How do I store repeated null characters in a string in C from fgetc?

EDIT: This simply doesn't work reliably with strings. I have changed the entire system to work with int arrays. Eliminated a bunch of other headaches, too. The working version of my MVC is:
#include <stdio.h>
#include <string.h>
int main (){
int nextChar;
int augmented[256];
int index = 0;
while ((nextChar = fgetc(stdin)) != EOF){
augmented[index] = nextChar;
index++;
}
for (int i = 0; i <= index;++i){
printf("%c", augmented[i]);
}
}
END EDIT
ORIGINAL POST:
I am trying to implement an LZW compressor for an assignment. So far, everything works great on text, but I am putting out garbage if the input file contains a long run of null characters.
Right at the start I store the incoming char as an int to check for EOF and then cast it to a char to concat to my augmented string for dictionary comparison. I have printed out my dictionary after each file and find that with long runs of zeros my dictionary entry is a null string.
I think that whats happening is that it takes a string of zeros and makes it a single zero. Not the desired value. I need to put out ALL those zeros.
I have made a minimal viable code to show the error and have found that it occurs right at the casting stage. How can I build a check for the null character so that I can substitute it for something else that can be stored in a string?
#include <stdio.h>
#include <string.h>
int main (){
int nextChar;
char augmented[256] = "\0";
while ((nextChar = fgetc(stdin) != EOF)){
char charBuffer[2];
sprintf(charBuffer, "%c", nextChar);
strcat(augmented, charBuffer);
}
printf("%s",augmented);
}
I've been searching for a couple days and I guess I can't seem to figure out what the correct query should be as I'm not finding any useful results.
The problem is parenthesis. Change to:
while ((nextChar = fgetc(stdin)) != EOF){
Your code assigned the value of the comparison fgetc(stdin)) != EOF to nextChar.
And you should also initialize charBuffer to zero.
here are some updates to your program. 0's are converted to '0's. Not exactly sure what you're looking for but hopefully this gets you pointed in the right direction:
#include <stdio.h>
#include <string.h>
int main (){
int nextChar;
char augmented[256] = {0}; // zero entire array
int i = 0;
while ((nextChar = fgetc(stdin)) != EOF){
// convert 0 to some other character
if( nextChar == 0 ) nextChar = '0';
augmented[i++] = (char)nextChar;
//check for buffer overflow
if( i==255) break;
}
printf("%s",augmented);
}

getchar() stuck in a loop never reaching the EOF

#include <stdio.h>
int main() {
int c;
while(getchar() != EOF) {
if (getchar() == ' ') {
c++;
}
printf("%i", c);
}
}
I realized that typing in a sentence like the one you're reading right
I\nrealized\nthat\ntyping\nin\n\a\n ...
i believe that's how it's being read, getchar() does not reach the EOF to make the condition in the while parentheses false..
my goal here is to make a program that takes in input from me..
reads it
if there are any spaces
it counts on a counter
when EOF is reached
the condition to keep reading it becomes false
the counter value gets printed out on the screen
to show me how many spaces i had in my entire input..
is it impossible? is that why people just use scanf() ?
this is the output i get when trying something
user#user:/c# ./a.out
hello stackoverflow this does not do what i want it to
001111111222223344445666677
You need to put the result of getchar() into a variable:
int ch;
while ((ch = getchar()) != EOF)
You shouldn't call getchar() a second time to check if it's a space, since that will read a second character so you'll be testing every other character, just compare the variable:
if (ch == ' ')
And if you want to see the total number of spaces, put the printf() at the end of the loop, not inside it.
So the whole thing should look like:
#include <stdio.h>
int main() {
int counter=0;
int ch;
while((ch = getchar()) != EOF) {
if (ch == ' ') {
counter++;
}
}
printf("%i\n", counter);
}
To send EOF from the terminal, type Control-d on Unix, Control-z on Windows.

Writer inserting unwanted newline character

I have 2 C functions that interact with one another. The first a writer function takes an int n and writes "Hellohello" n number of times. The reader function reads whatever is input to it, and every 50 characters inserts a newline character.
My current dilemma is that when I have a number of characters that is a factor of 50 my reader is putting an extra newline character in when I do not want it to. I have tried multiple different ways to remedy this and nothing I have attempted has worked as of yet. What I'm providing is my reader code without any of my attempted fixes as well as an example of what the problem is.
I do have to use getchar and putchar, I understand that there would be easier ways if I wasn't using them but it is unfortunately a must. Any assistance as to how I should approach this or something I should have thought about are greatly appreciated.
reader code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
char c;
while (c != EOF)
{
c = getchar();
if (count == 50)
{
putchar('\n');
count = 0;
}
putchar(c);
count++;
}
}
example output:
[88] [cbutc1#courses2016:~/csc412]$ writer 10 | reader1
HellohelloHellohelloHellohelloHellohelloHellohello
HellohelloHellohelloHellohelloHellohelloHellohello
▒[89] [cbutc1#courses2016:~/csc412]$
edit: clarity
When you read (getchar) a newline you print a newline (putchar).
Also, 'c' should be declared 'int'' so it is big enough to hold EOF properly.
Also the value of 'c' is undefined the first time through the loop and you print "EOF'", use:
while ((c = getchar()) != EOF) { …
Additionally, you should use int main ( void ) { …
And the C language does have "classes", only functions.
Simply changed the if statement that was checking the count to include a check for newline characters. This remedied the problem that was occuring.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
char c;
while (c != EOF)
{
c = getchar();
if ((count == 50) && (c != '\n'))
{
putchar('\n');
count = 0;
}
putchar(c);
count++;
}
}

File is not being opened when inputted. C

My issue is when I try to input spath as the first parameter for fopen(); is keeps looping wether the file exists or not. Yet, when i hard code the parameter to my test file it works properly.I am not sure what the issue is, maybe it is the syntax.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char spath[255], dpath[255];
int c;
FILE *sfp, *dfp;
do
{
printf("Please enter a source file:\n");
fgets(spath, sizeof(spath), stdin);
if(strlen(spath) > 253)
{
while((c = getchar()) != '\n' && c != EOF);
}
}while((sfp=fopen(spath,"r")) == NULL);
}
Upon further reading, fgets() has a new line character in the array which messes things up. To fix this use:
for(i = 0 ; i < lenght ; i++)
{
if(array[i] == '\n')
array[i] = '\0' ;
}
This takes away the new line character and insert a terminator character.
Click this link for further information: Open file with user input (string) - C

print multiple lines by getchar and putchar

Im a beginner learning The C Programming language and using Microsoft visual C++ to write and test code.
Below program in C from text(section 1.5.1) copy its input to its output through putchar() and getchar():
#include <stdio.h>
int main(void)
{ int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;}
The program print characters entered by keyboard every time pressing ENTER.As a result,I can only enter one line before printing. I can't find a way to enter multi-line text by keyboard before printing.
Is there any way and how to let this program input and output multi-line text from keyboard?
Sorry if this is a basic and ignorant question.
Appreciate your attention and thanks in advance.
Some clever use of pointer arithmetic to do what you want:
#include <stdio.h> /* this is for printf and fgets */
#include <string.h> /* this is for strcpy and strlen */
#define SIZE 255 /* using something like SIZE is nicer than just magic numbers */
int main()
{
char input_buffer[SIZE]; /* this will take user input */
char output_buffer[SIZE * 4]; /* as we will be storing multiple lines let's make this big enough */
int offset = 0; /* we will be storing the input at different offsets in the output buffer */
/* NULL is for error checking, if user enters only a new line, input is terminated */
while(fgets(input_buffer, SIZE, stdin) != NULL && input_buffer[0] != '\n')
{
strcpy(output_buffer + offset, input_buffer); /* copy input at offset into output */
offset += strlen(input_buffer); /* advance the offset by the length of the string */
}
printf("%s", output_buffer); /* print our input */
return 0;
}
And this is how I use it:
$ ./a.out
adas
asdasdsa
adsa
adas
asdasdsa
adsa
Everything is parroted back :)
I've used fgets, strcpy and strlen. Do look those up as they are very useful functions (and fgets is the recommended way to take user input).
Here as soon as you type '+' and press enter all the data you entered till then is printed. You can increase the size of array more then 100
#include <stdio.h>
int main(void)
{ int c='\0';
char ch[100];
int i=0;
while (c != EOF){
c = getchar();
ch[i]=c;
i++;
if(c=='+'){
for(int j=0;j<i;j++){
printf("%c",ch[j]);
}
}
}
return 0;
}
You can put a condition on '+' char or whatever character you would like to represent print action so that this character is not stored in the array ( I have not put any such condition on '+' right now)
Use setbuffer() to make stdout fully buffered (up to the size of the buffer).
#include <stdio.h>
#define BUFSIZE 8192
#define LINES 3
char buf[BUFSIZE];
int main(void)
{ int c;
int lines = 0;
setbuffer(stdout, buf, sizeof(buf));
while ((c = getchar()) != EOF) {
lines += (c == '\n');
putchar(c);
if (lines == LINES) {
fflush(stdout);
lines = 0;
}}
return 0;}
Could you use the GetKeyState function to check if the SHIFT key is held down as you press enter? That was you could enter multiple lines by using SHIFT/ENTER and send the whole thing using the plain ENTER key. Something like:
#include <stdio.h>
int main(void)
{ int c;
while (true){
c = getChar();
if (c == EOF && GetKeyState(VK_LSHIFT) {
putchar("\n");
continue;
else if(c == EOF) break;
else {
putchar(c);
}
}

Resources