I have already looked at this similar question but i am still wondering if there is another way to stop 1) the terminal echoing with portabilty as this is an assignment and I have already had one java program crash and burn on my teachers computer 2) in my program i search for a '\n' char then if it isn't the first char use getchar then putchar till the next '\n' char which works fine when using redirected stdin but when I try using the program without redirection the enter key is always echoed, is this to do with the terminal echoing or do i need to check for a diffrent char apart from '\n'? I have also tried including '/r' and done lots of googling but it seems the answer to the echo is can't be done with portabilty?
#include <stdio.h>
#include <string.h>
int first_line(char);
int main(){
char c;
while((c = getchar())!=EOF){
first_line(c);
}
return 0;
}
int first_line(char c){
if (c != '\n'||c != '\r'){
putchar(c);
do{
c = getchar();
putchar(c);}
while( c !='\n');
}
return 0;
}
Thanks Lachlan
For a start try with the following :
1) the condition should be if (c != '\n' && c != '\r')
2) and the while loop ,in case if terminal is line buffered then you are better of using getchfrom ncurses library the library packages should be there for most platforms.
while((c =getchar())!='\n') {
putchar(c);
}
Related
I'm writing a program which takes input and outputs it one word per line.
#include <stdio.h>
int main()
{
int c;
while( (c = getchar()) != EOF)
{
if( c != ' ')
putchar(c);
else
putchar('\n');
}
}
The program stops when it encounters the EOF character. When I input something like "Hello World^Z" (I am using Windows) I get the following output:
C:\Coding\C>a
Hello World^Z
Hello
World→
And it still waits for me to input something. What does the → symbol mean?
#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.
I am trying to solve an assignment question - "Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank". After writing the code, I am trying to compile it on a Mac terminal. I know how to compile using gcc command.
How do I give input from terminal to see what the output is?
The code that I have tried:
#include <stdio.h>
int main(void)
{
int c, inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace ==0)
{
inspace = 1;
putchar(c);
}
}
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
Use
gcc program.c
then run using :
./a.out
don't give enter, first type in some characters using your keyboard, then press enter. You'd need to type control-D at the beginning of a line to indicate EOF (or type it twice to indicate EOF without a newline as the last character). You could also interrupt the program with control-C.
Run command sequence:
gcc -Wall main.c -o a.out
./a.out < inputfile.txt
I want to read from file like ./a.out < inputfile.txt and after iterating char by char, print OK if all the characters are alphanumeric or ERROR otherwise. I can't seem to get this to work.
inputfile.txt
the brown fox jumped over the dog
this is another string
here is another string
main.c
int main() {
char c;
while (!feof(stdin)) {
c = getchar();
if (!isalnum(c)) {
printf("ERROR!\n");
exit(1);
}
}
printf("OK\n);
return 0;
}
As the others said - spaces and new lines are not alnum characters. Use isalnum() + isspace() in this case. In addition to that consider using some kind of a flag instead of using exit() function:
#include <stdio.h>
#include <ctype.h>
int main()
{
int c;
char ok='Y';
while(c = getchar())
{
if(c == EOF) break;
if(!isalnum(c) && !isspace(c))
{
ok = 'N';
break;
}
}
printf("%c\n", ok);
return 0;
}
RTFM: http://www.cplusplus.com/reference/cctype/
I swear this is the last time when I'm gonna help out people who can't even debug their codes.
A space is not an alphanumeric character.
See the table in this page for what is or isn't "isalnum".
You're using feof wrong. feof returns true when the EOF indicator has already been set, i.e: when you have already read an EOF. So when stdin reaches end-of-file you still get one loop iteration with EOF, which isn't an alpha-numeric character. In order to make sure you can properly distinguish EOF from any valid character you should declare c as an int. I suggest:
int c = getchar();
while(c != EOF){
if(!isalnum(c)){
printf("ERROR!\n");
exit(1);
}
c = getchar();
}
printf("OK\n");
This is my very first post on Stack Overflow, so I hope I don't step on anyone's toes.
Of course, all inputs are welcome and appreciated, but those most suited to answer would have actually read the book, C Programming Language, 2nd ed.
I have just finished coding Exercise 6-4, but I cannot seem to figure something out. Why does the getword() function not read EOF until I press Ctrl+D (I code in C in an Arch Linux VM)?
Many of my previous exercises from the book require reading from stdin. One way I would do it is via something like
while ((c = getchar()) != EOF) {...}
In such an instance, I never have to press Ctrl+D. I enter in my input, press Enter, the stdin buffer gets flushed out, and EOF is detected automatically. The getword() function also relies on getchar() at its base, so why does it hang my program?
The getword() function is called from main():
while (getword(word, MAX_WORD) != EOF) {
if (isalpha(word[0])) {
root = addtree(root, word);
}
}
The getword() function itself:
int getword(char *word, int lim) {
char *w = word;
int c;
while (isspace(c = getch())) {
}
if (c != EOF) {
*w++ = c;
}
// This point is reached
if (!isalpha(c)) {
// This point is never reached before Ctrl+D
*w = '\0';
return c;
}
for ( ; --lim > 0; w++) {
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
I put comments to indicate the point where I determined that EOF is not being read.
The getch() and ungetch() functions are the same ones used in the Polish notation calculator from Chapter 4 (and that program was able to read EOF automatically - by pressing Enter):
#define BUF_SIZE 100
char buf[BUF_SIZE];
int bufp = 0;
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if (bufp >= BUF_SIZE) {
printf("ungetch: too many characters\n");
}
else {
buf[bufp++] = c;
}
}
Thus far, this is the first program I wrote since the beginning of this book that requires me to manually enter the EOF via Ctrl+D. I just can't seem to figure out why.
Much appreciation in advance for explanations...
Having to type Ctrl+D to get EOF is the normal behavior for Unix-like systems.
For your code snippet:
while ((c = getchar()) != EOF) {...}
pressing Enter definitely shouldn't terminate the loop (unless your tty settings are badly messed up).
Try compiling and running this program:
#include <stdio.h>
int main( void )
{
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
It should print everything you type, and it should terminate only when you type control-D at the beginning of a line (or when you kill it with control-C).
The 'not reached' point would only be reached if you did something like type a punctuation mark in the input - or you read EOF. If you type a letter, or spaces, then it is bypassed.
When input is coming from a terminal (standard input), then EOF is not detected until you type Control-D (or whatever is specified in the stty -a output) after you enter a newline, or after you hit another Control-D (so two in a row). The code reads through newlines because the newline character '\n' satisfies isspace().
The source of my confusion vis-a-vis my previous programs was that the effect of my previous programs were always printed to stdout inside the while loop, so I always immediately saw the result without needing to feed in EOF. For this one, the tree is not printed until after the while loop ends, so the EOF encounter was needed. I failed to recognize that, and that's why I was going insane.
Thanks again for setting me straight!