Code prints out correctly with a leading space. - c

I'm new to C programming and I'm having probably a simple issue.
I've looked all over the site looking for an answer to this but my no luck.
So my program runs fine if at the end of the input file there is a space. For example running the program from command line in unix
./program-name < file.txt
if the file.txt is
//with a space whith | | being a space.
The Cat Ran.| |
I get the correct output 1 1 1
if it is
The Cat Ran.(With no space I get 1 1)
//I have to use C for this program.
#include <stdio.h>
int main(void){
int i=0;
char c;
int NOV=0;
while( (c=getchar())!=EOF && c !='\n' && c !=10 ){
if( c=='a'||c=='e'||c=='i'||c=='o'||c=='u' ){
NOV++;
}
if(c==' '){
printf("%d ",NOV);
NOV=0;
}
}
printf("\n");
return 0;
}
Any Help is appreciated.

The trouble is that when you get EOF without a space, you exit the loop, and nothing after the loop prints the number of vowels.
Add if (NOV != 0) printf("%d", NOV); after the loop, perhaps.
Separately, your use of 10 is odd; '\n' is control-J or 10. You might be thinking of control-M, aka carriage return or '\r'.
Also, as Blue Pixy pointed out in a comment, you should always use int c; to receive the return from getchar() or getc() of fgetc(). The functions return an int, which may be any value that fits in an unsigned char or EOF, a negative value. You run into problems if you use char c instead.

Your program should read like this (a lot of useless clutter has been removed) :
int main(void)
{
int c;
int nov = 0;
while( (c = getchar()) != EOF && c != '\n')
{
if( c=='a'||c=='e'||c=='i'||c=='o'||c=='u' )
nov++;
}
printf("%d\n", nov) ;
return 0;
}

Related

Copying the input from `getchar()` to another variable

In the following code example from K&R's book, if I replace putchar(c) with printf("%c", c) the code works the same. But if I replace it with printf("%d", c) it gives gibberish output.
#include <stdio.h>
int main() {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
From here, I learned that the getchar() converts the stdin to an 8-bit character whose value ranges from 0 to 255.
Now I want to print the value of c using putchar(c) in one line and printf("%d", c) in another line. So I wrote the following code:
#include <stdio.h>
int main() {
int c, b;
c = getchar();
b = c;
while (c != EOF && c != 10) {
printf("%c",c);
c = getchar();
}
printf("\n");
while (b != EOF && b != 10) {
printf("%d\t",b);
b = getchar();
}
}
I used the condition c != 10 as the newline character is read as 10 by getchar(). I expected the code to work as
$ ./a.out
783
783
55 56 51
but the program terminates as
$ ./a.out
783
783
55
I understand that getchar() takes input from stdin and the variable b is not stdin. So how should I copy the variable c to b so that my program works as I expect it to?
The problem is that your code does not (and cannot, as it stands) 'remember' the inputs you gave in the first loop. So, after you have finished that loop, your second loop is wanting to read in the characters for b (after it has output the first value, which is remembered from the earlier b = c line).
So, after outputting 55 (the integer value of the character 7), it is waiting for further input.
Probably the easiest way to get the output that you're looking for is to have an array of input characters. Then, you can output the %c values as you read them (as before), then re-run the outputs using the %d format in a subsequent for loop.
Here is a demonstration that does what I think you're after:
#include <stdio.h>
#define MAXINS 20 // Set to the maximum number of input characters you want to allow
int main()
{
int c[MAXINS];
int i = 0, n = 0;
c[0] = getchar();
while (i < MAXINS && c[i] != EOF && c[i] != 10) {
printf("%c", c[i]);
c[++i] = getchar();
++n;
}
printf("\n");
for (i = 0; i < n; ++i) {
printf("%d\t", (int)(c[i]));
}
return 0;
}
Feel free to ask for further clarification and/or explanation.
EDIT: On the point in the your first paragraph, "But if I replace it with printf("%d", c) it gives gibberish output." Well, when I try the following code and give 783 and then hit return (which generates a newline) I get the expected 55565110 as the output:
int main()
{
int c;
c = getchar();
while (c != EOF) {
printf("%d", c);
c = getchar();
}
return 0;
}
This may look like gibberish, but it's just the same output as you 'expect' in your later code, but without the spaces and with the addition of the 10 for the newline.
You need to have every character stored, because once you read a char from stdin, it is not present in stdin anymore.
Since you want the newline character in the end as a part of the input, you should use fgets to take the input.
Say you are taking an input that could have a maximum of 100 characters.
#include <stdio.h>
int main(void) {
char c[100]; // A char array
fgets(c,100,stdin);
int x=0;
while (c[x] != 10 && c[x] != EOF)
printf("%c",c[x++]);
printf("\n");
x = 0;
while (c[x] != 10 && c[x] != EOF) // You can simply compare it with the newline character too.
printf("%d ",c[x++]);
printf("\n");
return 0;
}
There are many ways to do this. You can also read stdin character-by-character ans store it in an array. However, since you need to display the ASCII values of the characters in another line after displaying the characters themselves, you will have to store them in an array.
You are copying only the first input, to copy the whole string you need to store each input in a buffer and check if the string doesn't overflow that buffer on each iteration:
int main(void)
{
enum {size = 256};
char buffer[size];
size_t count = 0;
int c;
while ((c = getchar()) && (c != '\n') && (c != EOF))
{
printf("%c", c);
if (count < size)
{
buffer[count++] = (char)c;
}
}
printf("\n");
for (size_t iter = 0; iter < count; iter++)
{
printf("%d\t", buffer[iter]);
}
printf("\n");
}
If you don't want to limit the buffer to an arbitrary size then you need to change your approach to use dynamic memory (realloc or a linked list)

Printing lowercase, uppercase, and number of numbers

#include<stdio.h>
int main() {
char text[1000];
int ch;
int index = 0;
while ((ch = getchar()) != EOF) {
text[index] = ch;
index++;
}
text[index] = '\0';
int i =0;
int num_Count=0;
int lower_Count=0;
int upper_Count =0;
while(i < index) {
if((text[i]>='0') && (text[i]<='9')){
num_Count ++;
i++;
}
else if((text[i]>='A') && (text[i]<='Z')){
upper_Count++;
i++;
}
else if((text[i]>='a') && (text[i] <='z')){
lower_Count++;
i++;
}
else
i++;
}
printf("%d %d %d", num_Count, lower_Count, upper_Count);
return 0;
}
It is a program that outputs the number of lower case, upper case, and number when the sentence is inputted.
For example,
Hi
Name
100
Would output 3 4 2
I keep seeing a runtime error.
The (while) part seems to be wrong.. I do not know what's wrong.
I ran your code in my system and checked for the input: Hi Name 100. The output I got is 3 4 2 which is the expected output. I feel the only place where the code can run in an infinite loop is while reading the inputs. Try to use ctrl+ d for EOF or ctrl+ z for windows.
Rest every thing is fine.
EOF means End Of File. It is used when you read data from a file. I suggest put a character like newline ('\n').

Problems with a character counting program in C on online compilers

I'm a newcomer to programming so please forgive me for my stupid questions. I ran the following code on repl.it and JDoodle respectively.
#include<stdio.h>
int main()
{
int nc;
nc = 0;
while(getchar() != EOF)
nc = nc + 1;
printf("%d\n", nc);
}
On JDoodle, the results are always x+1 where x is the number I expected. For example, if I input 123123, the result is 7. Besides, if I leave the input empty, JDoodle tells me that Your Program may have a endless loop. Why these happen?
On repl.it, after I type the input on the right side of the screen and press Enter, there is no response. However the input copying program
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
works well on repl.it. Why the character counting program cannot work on repl.it? I will appreciate any help with these situations.
the following proposed code:
corrects the problem discussed in the comments to the question.
The differences between the two web pages is of no consequence to the problem seen by the OP.
And now the proposed code:
#include <stdio.h>
int main( void )
{
int nc = 0;
int ch; // the character input from stdin
while( (ch = getchar()) != EOF && '\n' != ch)
nc = nc + 1;
printf("%d\n", nc);
}

k and r line counting 1.5.3 not working?

I'm having trouble with k&r 1.5.3. Obviously I'm a complete beginner. Below is the code exactly from the book and exactly as I typed it. It compiled fine and runs. It returns characters but just never prints the line count. I'm using ssh into a Ubuntu machine. Can the key on my wife's mac not be interpreted as '\n'?
#include <stdio.h>
/*count lines in input*/
main()
{
int c, n1;
n1 = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++n1;
printf("%d\n", n1);
}
Correct. Mac uses \r as line ending: http://en.wikipedia.org/wiki/Newline
Update your code like this:
#include <stdio.h>
/*count lines in input*/
main()
{
int c, n1;
n1 = 0;
while ((c = getchar()) != EOF)
if (c == '\r') /* use \r for Macs */
++n1;
printf("%d\n", n1);
}
However
When I try to do the same, I have to Ctrl-D to enter an EOF and trigger the program to print the line count.

The C Programming Language by K&R Examples CH1

I am going through this book and have hit some examples that I am not sure how to test from chapter 1. They have you reading in lines and looking for different characters but I have no idea how to test the code in C that I have made.
For example:
/* K&R2: 1.9, Character Arrays, exercise 1.17
STATEMENT:
write a programme to print all the input lines
longer thans 80 characters.
*/
<pre>
#include<stdio.h>
#define MAXLINE 1000
#define MAXLENGTH 81
int getline(char [], int max);
void copy(char from[], char to[]);
int main()
{
int len = 0; /* current line length */
char line[MAXLINE]; /* current input line */
while((len = getline(line, MAXLINE)) > 0)
{
if(len > MAXLENGTH)
printf("LINE-CONTENTS: %s\n", line);
}
return 0;
}
int getline(char line[], int max)
{
int i = 0;
int c = 0;
for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
line[i] = c;
if(c == '\n')
line[i++] = c;
line[i] = '\0';
return i;
}
I have no idea how to create a file with varying line lengths to test this on. After doing some research I saw someone try it this way:
[arch#voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-17.c
[arch#voodo kr2]$ ./a.out
like htis
and
this line has more than 80 characters in it so it will get printed on the terminal right
now without any troubles. you can see for yourself
LINE-CONTENTS: this line has more than 80 characters in it so it will get printed on the
terminal right now without any troubles. you can see for yourself
but this will not get printed
[arch#voodo kr2]$
But I have no idea how he manages it. Any help would be greatly appreciated.
for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
This is the line that tells you everything you need to know about your getline() function.
It will read character by character and store it in the array until:
You don't press ^D(linux)/^Z(win) on the terminal(^ = control)
You don't press "enter" key on your keyboard
The number of characters entered shouldn't be more than max - 1. Otherwise they'll not be copied. In your example max = 1000 hence only 999 characters are input.
That program reads the standard input. If you just type exactly what is shown in that example, you'll see the same output. Enter a ^D to end your program.

Resources