getchar() in C with while looping not printing afterwards - c

I don't understand why the printf() call after the while loop does not get executed?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}

I think you are trying to do that
#include<stdio.h>
int main()
{
int characters=0,lines=0;
char ch;
while((ch=getchar())!= EOF)
{
if (ch == '\n')
lines++;
else
{
characters++;
while((ch=getchar())!='\n'&&ch!=EOF); //is to remove \n after a character
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
Output:
a
s
d
f
^Z
lines: 1
Chars: 4
Process returned 0 (0x0) execution time : 8.654 s
Press any key to continue.
Note: ^Z(ctrl+z) is to send EOF to stdin (in windows)

You have to be careful of you're treatment in the while loop. Indeed, you are missing every caracter read in your while statement. You have to save this input, in order to use it afterwards.
The proper syntax would be while(( c = getchar()) != EOF)

You are probably looking for something like this:
#include <stdio.h>
int main()
{
int characters = 0;
int lines = 0;
int c;
while ((c = getchar()) != EOF) {
characters++;
if (c == '\n') {
lines++;
characters--; // ignore \n
}
}
printf("lines: %8d\n", lines);
printf("Chars: %8d", characters);
return 0;
}
while ((c = getchar()) != EOF) might look a bit confusing.
Basically it calls getchar, puts the returned valuee into c ands then checks if c equals EOF.

Related

Copying input to output without unnecessary Spaces in C

I'm trying to write a program in C that copies its input to its output while replacing each string of one or more Spaces with a single Space.
My code isn't doing that but is instead taking away every second character.
This is my code:
#include <stdio.h>
main()
{
int c;
int lastc;
lastc = 0;
while(getchar() != EOF){
c = getchar();
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
}
Your loop should look like:
while((c = getchar()) != EOF){
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
In your version you get a char with getchar while checking the condition for the while loop and then as a next step you again get a char with getchar. So the first one is not used in your code. Therefore it is taking away every second character.
Keep running in while loop until you get non-space character and print just one space after you get out.
int main()
{
int c;
bool space=false;
while ((c=getchar()) != EOF) {
while (isspace(c)) {
space = true;
c = getchar();
}
if (space) {
putchar(' ');
space = false;
}
putchar(c);
}
return 0;
}
I use fgets() function to getting string from input i.e stdin and store in the scroll string.
Then you must implement a way to analyze string to find spaces in it.
When you find first space, increase index if you face another space.
This is the code.
Code
#include <stdio.h>
int main(void){
char scroll[100];// = "kang c heng junga";
fgets(scroll, 100, stdin);
printf ("Full name: %s\n", scroll);
int flag = 0;
int i=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
printf("%c",scroll[i]);
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
return 0;
}
Sample input: Salam be shoma doostane aziz
Program output: Salam be shoma doostane aziz
[Edit]
Use new string st to hold space eliminated string an print as output.
Also this code work for Persian string.
char scroll[100]={0};// = "kang c heng junga";
printf("Enter a string: ");
fgets(scroll, 100, stdin);
printf ("Original string: %s\n", scroll);
char st[100]={0};
int flag = 0;
int i=0;
int j=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
st[j]=scroll[i];
j++;
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
printf("Eliminate Spaces: %s", st);

C code only prints after ^Z

I'm reading K&R's book on C and i got to this part where the output would be the number of newlines that you input.I wanted to make it so that it prints out each number corresponding to the amount of newlines typed as the lines are being read.This only outputs the value of nl after F6 or CTRL+Z has been pressed(EOF).Could someone explain to me why?
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
You forgot some brackets. Here's what your code does currently:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
}
}
printf("%d\n", nl);
}
Here's what you probably wanted to do based of indentation:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
printf("%d\n", nl);
}
}
}
In C, whitespace is mostly ignored. If you want to run multiple statements together in a block, you need to surround that code with brackets {}
The while loop ends only when the character is an EOF character. EOF is a special character that represents the end of the file the program is reading. Since you are reading from the console, the console itself is the file you are reading from but it as no end. However in your system you can send an EOF character to the console by typing F6 or CTRL+Z
Instead if you want to print the number of lines while typing you should change your code like this:
int main(){
int c, nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
printf("%d\n", nl);
}
}
}

Counting input characters in C

I have just started learning C, been reading a C textbook by Keringhan and Ritchie. There was this example in the textbook, counting characters from user input. Here's the code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF) {
if (getchar() != 'q')
++nc;
else
break;
}
printf("%ld\n", nc);
}
The problem is, when I execute the code, if I input only one character per line, when I input "q" to break, it doesn't do so. I have to type some word per line, only after that it will break the loop. Also, it only counts the half of the characters of the word. I.e. if I input
a
b
russia
it will only print '5' as final result.
Could you please explain to me why is this happening?
This works, but only when you finish off with an Enter. So, this will count the characters until the first "q" appears. That is just how getchar() and getc(stdin) work.
#include <stdio.h>
int main() {
char c = 0;
long count = 0;
short int count_linebreak = 1; // or 0
while((c = getchar()) != EOF) {
if(c != 'q' && (count_linebreak || (!count_linebreak && c != '\n'))) {
++count;
}else if(c == 'q') {
printf("Quit\n");
break;
}
}
printf("Count: %ld\n",count);
return 0;
}
A StackOverflow question about reading stdin before enter
C read stdin buffer before it is submit

How to count number of characters without the newline character?

Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..
the code:
#include <stdio.h>
int main()
{
char ch;
int numberOfCharacters = 0;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((ch = getchar()) != EOF)
{
if (numberOfCharacters != '\n')
{
numberOfCharacters++;
}
}
printf("The number of characters is %d", numberOfCharacters);
return 0;
}
what am i doing wrong?
Think about this line:
if (numberOfCharacters != '\n')
how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...
Change your loop to this.
while ((ch = getchar()) != EOF)
{
if(ch != '\n')
numberOfCharacters++;
}

Reading enter key in a loop in C

How can I read the enter key in a loop multiple times?
I've tried the following with no result.
char c;
for (i=0; i<n; i++){
c = getchar ();
fflushstdin ();
if (c == '\n'){
//do something
}
}
And fflushstdin:
void fflushstdin (){
int c;
while ((c = fgetc (stdin)) != EOF && c != '\n');
}
If I read any other character instead of enter key it works perfect, but with enter key In some iterations I have to press the enter 2 times.
Thanks.
EDIT: I'm executing the program through putty on windows and the program is running on a virtualized linux mint on virtual box.
Why do you call fflushstdin()? If fgetc() returns something different from \n, that character is completely dropped.
This should work:
char prev = 0;
while(1)
{
char c = getchar();
if(c == '\n' && prev == c)
{
// double return pressed!
break;
}
prev = c;
}
Try
if (ch == 13) {
//do something
}
ASCII value of enter is 13, sometimes \n won't work.
You should go with:
char c;
for (i=0; i<n; i++){
c = getchar ();
fflushstdin ();
if (c == 13){
//do something
}
}
since 13 is ASCII code for Enter key.
You always executing getchar twice (even when there is no need for that). Try limiting calls to fflushstdin:
char c;
for (i=0; i<n; i++){
c = getchar ();
if ((c != EOF) && (c != '\n')) fflushstdin ();
if (c == '\n'){
//do something
}
}

Resources