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.
Related
This is my C code:
#include <stdio.h>
int main()
{
int c = getchar();
while (c != EOF) {
if (c != '\n')
putchar(c);
else putchar(32);
c = getchar();
}
return 0;
}
I want to make a program that prints out a paragraph with newlines, by replacing the \n character with spaces. The problem is, it only prints out the last line, when I use the code provided above.
For, example, for the text:
This is
my
text
the result printed is text.
The paragraph is properly printed when I remove the if(), else conditions, and only leave the putchar(), without trying to replace anything.
What's the problem?
Your input file has CRLF newlines. You need to ignore the CR characters when you're replacing LF with space. Otherwise, printing the CR characters will go back to the beginning of the line and overwrite what was already printed.
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c == '\n') {
// replace newline with space
putchar(' ');
} else if (c == '\r') {
// ignore CR
} else {
putchar(c);
}
}
return 0;
}
I am attempting to reverse my lines within a text file using the recursion method. I am pretty stuck right now and my current output is a Segmentation Error- Can someone explain what the segmentation error is from and push me in the right direction?
void RecursionLine();
int main (int argc, char argv)
{
RecursionLine();
printf("\n");
}
void RecursionLine()
{
int c;
if((c = getchar()) != EOF || (c != '\n'))
{
RecursionLine();
printf("%c",c);
}
else if((c = getchar()) != EOF && (c == '\n')){
printf("\n");
RecursionLine();
}
}
Input:
Dogs
Cats
Boys
Output
sgoD
staC
syoB
You are getting a Segmentation error because you have an || condition in your first if statement, where one of those conditions will always be true, causing your stack to overflow from infinite recursion! Change this to an && and it should be all fixed!
if((c = getchar()) != EOF && (c != '\n'))
EDIT: Additionally I believe you are going to run into some improper functionality due to the second getchar(). I would change your function to:
void RecursionLine()
{
int c = getchar();
if(c != EOF || c != '\n')
{
RecursionLine();
printf("%c",c);
}
else if(c != EOF && c == '\n'){
printf("\n");
RecursionLine();
}
}
Otherwise you are going to read in potentially 2 characters every iteration and that is going to cause one/both of them to be skipped!
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;
}
This program is supposed to remove all comments from a C source code (in this case comments are considered double slashes '//' and a newline character '\n' and anything in between them, and also anything between '/* ' and '*/'.
The program:
#include <stdio.h>
/* This is a multi line comment
testing */
int main() {
int c;
while ((c = getchar()) != EOF)
{
if (c == '/') //Possible comment
{
c = getchar();
if (c == '/') // Single line comment
while (c = getchar()) //While there is a character and is not EOF
if (c == '\n') //If a space character is found, end of comment reached, end loop
break;
else if (c == '*') //Multi line comment
{
while (c = getchar()) //While there is a character and it is not EOF
{
if (c == '*' && getchar() == '/') //If c equals '*' and the next character equals '/', end of comment reached, end loop
break;
}
}
else putchar('/'); putchar(c); //If not comment, print '/' and the character next to it
}
else putchar(c); //if not comment, print character
}
}
After I use this source code as its own input, this is the output I get:
#include <stdio.h>
* This is a multi line comment
testing *
int main() {
int c;
while ((c = getchar()) != EOF)
{
if (c == '') ////////////////
{
c = getchar();
if (c == '') ////////////////////
while (c = getchar()) /////////////////////////////////////////
if (c == '\n') ///////////////////////////////////////////////////////////////
break;
else if (c == '*') ///////////////////
{
while (c = getchar()) ////////////////////////////////////////////
{
No more beyond this point. I'm compiling it using g++ on the ubuntu terminal.
As you can see, multi lines comments had only their '/' characters removed, while single line ones, had all their characters replaced by '/'. Apart from that, any '/' characters that were NOT the beginning of a new comment were also removed, as in the line if (c == ''), which was supposed to be if (c == '/').
Does anybody know why? thanks.
C does not take notice of the way you indent your code. It only cares about its own grammar.
Look carefully at your elses and think about which if they attach to (hint: the closest open one).
There are other bugs, as well. EOF is not 0, so only the first while is correct. And what happens if the comment looks like this: /* something **/?
You have some (apparent) logic errors...
1.
while (c = getchar()) //While there is a character and is not EOF
You're assuming that EOF == 0. Why not be explicit and change the preceding line to:
while((c = getchar()) != EOF)
2.
else putchar('/'); putchar(c);
Are both of the putchars supposed to be part of the else clause? If so, you need braces {} around the two putchar statements. Also, give each putchar its own line; it not only looks nicer but it's more readable.
Conclusion
Other than what I've mentioned, your logic looks sound.
As already mentioned, the if/else matching is incorrect. One aditional missing functionality is that you must make it more stateful to keep track of whether you are inside a string or not, e.g.
printf("This is not // a comment\n");
#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);
}