#include <stdio.h>
main(void) {
char ch;
while (1) {
if ((ch = getchar()) != EOF)
{
break;
}
putchar(ch);
}
return 0;
}
How do I escape from this while? I had tried with EOF but it didn't work.
I think you mean:
int ch;
Because EOF won't fit in a char.
Also:
if ((ch=getchar()) == EOF)
break;
Your logic is backwards.
This:
char ch;
is wrong, EOF doesn't fit in a char. The type of getchar()'s return value is int so this code should be:
int ch;
Also, as pointed out, your logic is backwards. It loop while ch is not EOF, so you can just put it in the while:
while((ch = getchar()) != EOF)
check with the while. It's more simple
while((ch=getchar())!= EOF) {
putchar(ch);
}
The EOF is used to indicate the end of a file. If you are reading character from stdin, You can stop this while loop by entering:
EOF = CTRL + D (for Linux)
EOF = CTRL + Z (for Windows)
You can make your check also with Escape chracter or \n charcter
Example
while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC
putchar(ch);
}
Related
#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 wrote a short program to test reading text files from stdin:
int main(){
char c;
while(!feof(stdin)){
c = getchar(); //on last iteration, this returns '\n'
if(!isspace(c)) //so this is false
putchar(c);
//remove spaces
while (!feof(stdin) && isspace(c)){ //and this is true
c = getchar(); // <-- stops here after last \n
if(!isspace(c)){
ungetc(c, stdin);
putchar('\n');
}
}
}
return 0;
}
I then pass it a small text file:
jimmy 8
phil 6
joey 7
with the last line (joey 7) terminated with a \n character.
My problem is, after it reads and prints the last line, then loops back to check for more input, there are no more characters to read and it just stops at the line noted in the code block.
Question: The only way for feof() to return true is after a failed read as noted here: Detecting EOF in C. Why isn't the final call to getchar triggering EOF and how can I better handle this event?
There are multiple problems in your code:
You do not include <stdio.h>, nor <ctype.h>, or at least you did not post the whole source code.
You use feof() to check for end of file. This is almost never the right method, as underscored in Why is “while ( !feof (file) )” always wrong?
You read the byte from the stream in a char variable. This prevents proper testing for EOF and also causes undefined behavior for isspace(c). Change the type to int.
Here is an improved version:
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (!isspace(c)) {
putchar(c);
} else {
//remove spaces
while ((c = getchar()) != EOF && isspace(c)) {
continue; // just ignore extra spaces
}
putchar('\n');
if (c == EOF)
break;
ungetc(c, stdin);
}
}
return 0;
}
While your method with ungetc() is functionally correct, it would be better to use an auxiliary variable this way:
#include <stdio.h>
#include <ctype.h>
int main(void) {
int c, last;
for (last = '\n'; ((c = getchar()) != EOF; last = c) {
if (!isspace(c)) {
putchar(c);
} else
if (!isspace(last))
putchar('\n');
}
}
return 0;
}
while((c = getc(file)) != -1)
{
if (c == ';')
{
//here I want to skip the line that starts with ;
//I don't want to read any more characters on this line
}
else
{
do
{
//Here I do my stuff
}while (c != -1 && c != '\n');//until end of file
}
}
Can I completely skip a line using getc if first character of line is a semicolon?
Your code contains a couple of references to -1. I suspect that you're assuming that EOF is -1. That's a common value, but it is simply required to be a negative value — any negative value that will fit in an int. Do not get into bad habits at the start of your career. Write EOF where you are checking for EOF (and don't write EOF where you are checking for -1).
int c;
while ((c = getc(file)) != EOF)
{
if (c == ';')
{
// Gobble the rest of the line, or up until EOF
while ((c = getc(file)) != EOF && c != '\n')
;
}
else
{
do
{
//Here I do my stuff
…
} while ((c = getc(file)) != EOF && c != '\n');
}
}
Note that getc() returns an int so c is declared as an int.
Let's assume that by "line" you mean a string of characters until you hit a designated end-of-line character (here assumed as \n, different systems use different characters or character sequences like \r\n). Then whether the current character c is in a semicolon-started line or not becomes a state information which you need to maintain across different iterations of the while-loop. For example:
bool is_new_line = true;
bool starts_with_semicolon = false;
int c;
while ((c = getc(file) != EOF) {
if (is_new_line) {
starts_with_semicolon = c == ';';
}
if (!starts_with_semicolon) {
// Process the character.
}
// If c is '\n', then next letter starts a new line.
is_new_line = c == '\n';
}
The code is just to illustrate the principle -- it's not tested or anything.
I know I can get the first character of a line of standard input by using getchar(), but I only want the first character of each line. Is there a function I can use to get rid of the rest of the string entered into standard input (if it is more than one character)? if not, what methodology should I consider using to get rid of the rest of the standard input line?
char buf[100];
while(fgets(buf,sizeof(buf),stdin) != NULL)
{
if(strlen(buf)>0)
buf[1] = '\0';
printf("%s",buf);
}
Read the whole line using fgets() and just nul terminate it after the first character.
#include <stdio.h>
int main(void)
{
int ch;
size_t len;
for (len = 0; 1; ) {
ch = getc(stdin);
if (ch == EOF) break;
if (!len++) putc(ch, stdout); /* the first character on a line */
if (ch == '\n') len = 0; /* the line has ended */
}
return 0;
}
Please note that the first character on a line can actually be a '\n' !!!
// Get the character you need
char c = getchar();
// Skip the rest
int a;
while((a = getchar()) != '\n' && a != EOF);
If you know how many lines you'll have, you can put it in a loop.
I don't understand.
I try to write a program to eliminate white spaces:
int c;
c = getchar();
while (c!= EOF) {
//do things
}
The above code causes a lot of the first input characters to output to screen,
yet
while ((c = getchar()) != EOF)
solved the problem.
Why?
How do I debug to understand this better?
while ((c = getchar()) != EOF)
solved the problem
Because your are calling getchar() on each iteration, and in the first code you wasn't.
Try this
#include <ctype.h>
#include <stdio.h>
void removeSpaces()
{
do {
chr = getchar();
} while ((chr != EOF) && (isspace(chr) != 0));
}
then just call removeSpaces() whenever you want to remove spaces.