started C this semester and struggling to convert knowledge of java into C. The code compiles and runs but not as I want it. The task is to write a code that read a text file line by line (I have a get line function) and outputs new text file keeping line formatting the same (meaning that if original file has 4 line output file has to have 4 line) but deleting trailing characters (space and \t). I've spend enormous amount of time pocking at this thing without success. Any help is appreciated.
hw2_execcise_1. program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.
Pseudo::: while (there are lines to read)
find end of line1 (\n)
save length
going from the end of the line towards the beginning
find char that is not either space or tab
and insert \n following found char.
#include <stdio.h>
#define LINELIM 1000
int getLine(char s[], int lim);
int main (void){
int len, i;
char line1[100];
while ((len = getLine(line1, LINELIM)) >0){
for (i=len; i>=0; i--){
if ((line1[i] == ' ') || (line1[i] == '\t')){
line1[i] = '\n';
}
else break;
}
printf(" %s\n", line1);
}
return 0;
}
/*getline: read a line into s, return length*/
int getLine(char s[], int lim){
int c,i;
for (i=0; i<lim-1 && (c=getchar())!= EOF && c!='\n'; ++i)
s[i]=c;
if (c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
while ((len = getLine(line1, LINELIM)) >0){
for (i=len-1; i>=0; i--){//-1 for 0 origin
if(line1[i] == ' ' || line1[i] == '\t' || line1[i] == '\n'){//add case of '\n'
line1[i] = '\0';//newline add print part
}
else break;
}
if(line1[0])//not blank line
printf("%s\n", line1);
}
the main logic problem with the code is
1) the getline function is terminating each input line with (either) '\n''\0' or with '\0'
2) the main function is not checking for the newline when it checks for space or tab. I.E. it needs to also check for newline --or-- getline() should not ever include the newline
Related
Hi i am writing a program to count the number of lines the user enters, i have this code:
#include <stdio.h>
#include <string.h>
int readline(char line[], int max);
/* count lines in input */
main() {
int c, nl,max, i;
max = 99;
char line[100];
nl = 0;
while (( readline(line, max) != 0)){
++nl;
}
printf("%d\n", nl);
}
/* readline: read a line from standard input, return its length or 0
*/
int readline(char line[], int max)
{
if (fgets(line, max, stdin) == NULL)
return 0;
else
return strlen(line);
}
but i am not sure how to terminate the program and have "nl" printed to the screen, i am using the cygwin64 terminal to write and execute the program.
Thanks
size_t n;
while(fgets(line,max,stdin))
{
n = strlen(line);
if( n == 1 && line[n-1] == '\n')
{
//This is a empty line
}
}
Basically fgets() comes with a newline character and you can use this to confirm whether there was any input in the line or just a newline character was entered.
readline returns the text of the line read. A blank line returns
the
empty string. If EOF is encountered while reading a line, and the line
is empty, NULL is returned. If an EOF is read with a non-empty line,
it is treated as a newline.
So you can check for empty string.
Change the condition into like this,
while (( readline(line, max) <= 1)){
...
}
When you enter the empty new line then that new line will be placed in that array.
So it gives the strlen as 1.
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 need to write a program that prints its input one word per line. Here's what I got so far:
#include <stdio.h>
main(){
int c;
while ((c = getchar()) != EOF){
if (c != ' ' || c!='\n' || c!='\t')
printf("%c", c);
else
printf("\n");
}
}
The logic is pretty simple. I check to see if the input is not a newline, tab or space, and in that case it prints it, otherwise prints a newline.
When I run it, I get results like this:
input--> This is
output--> This is
It prints the whole thing. What goes wrong here?
if (c != ' ' || c!='\n' || c!='\t')
This will never be false.
Perhaps you meant:
if (c != ' ' && c!='\n' && c!='\t')
instead of using printf try putchar, also as per above comments, you should use && instead of ||.
here is my code-
#include<stdio.h>
main()
{
int c, nw; /* nw for word & c for character*/
while ( ( c = getchar() ) != EOF ){
if ( c != ' ' && c != '\n' && c != '\t')
nw = c;
else {
nw = '\n';
}
putchar (nw);
}
}
this code will give you the desired output
you can use if you want the strtok function in string.h library which can cut the input into many words by providing a delimiter.
Here is a perfect code commented which can fit to your needs
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char line[1000]=""; // the line that you will enter in the input
printf("Input the line:\n>>");
scanf("%[^\n]",line); // read the line till the you hit enter button
char *p=strtok(line," !#$%&'()*+,-./'"); // cut the line into words
// delimiter here are punctuation characters (blank)!#$%&'()*+,-./'
printf("\nThese are the words written in the line :\n");
printf("----------------------------------------\n");
while (p!=NULL) // a loop to extract the words one by one
{
printf("%s\n",p); // print each word
p=strtok(NULL," !#$%&'()*+,-./'"); // repeat till p is null
}
return 0;
}
If we execute the code above we will get
Input the line:
>>hello every body how are you !
These are the words written in the line :
----------------------------------------
hello
every
body
how
are
you
suggest the code implement a state machine,
where there are two states, in-a-word and not-in-a-word.
Also, there are numerous other characters that could be read
(I.E. ',' '.' '?' etc) that need to be check for.
the general logic:
state = not-in-a-word
output '\n'
get first char
loop until eof
if char is in range a...z or in range A...Z
then
output char
state = in-a-word
else if state == in-a-word
then
output '\n'
state = not-in-a-word
else
do nothing
end if
get next char
end loop
output '\n'
I think the simple solution would be like
#include <stdio.h>
int main(void) {
// your code goes here
int c;
while((c=getchar())!=EOF)
{
if(c==' ' || c=='\t' || c=='\b')
{
printf("\n");
while(c==' ' || c=='\t' || c=='\b')
c=getchar();
}
if(c!=EOF)
putchar(c);
}
return 0;
}
I am trying to get fgetc to read through a file and skip from a certain indicator until a new line. This seems like a simple question, but I can't find any documentation on it.
Here is an example of my question:
read this in ; skip from semicolon on to new line
My best guess at a solution would be to read in the entire file, and for each line use strtok to skip from ; to the end of the line. Obviously this is horrible inefficient. Any ideas?
*I need to use fgetc or something like fgetc that will parse the file character by character
Easiest thing to do is read the entire line in, then truncate if there a ;.
char buffer[1024], * p ;
if ( fgets(buffer, sizeof(buffer), fin) )
{
if (( p= strchr( buffer, ';' ))) { *p = '\0' ; } // chop off ; and anything after
for ( p= buffer ; ( * p ) ; ++ p )
{
char c= * p ;
// do what you want with each character c here.
}
}
When you do the read, buffer will initially contain:
"read this in ; skip from semicolon on to new line\n\0"
After you find the ; in the line and stick a '\0' there, the buffer looks like:
"read this in \0 skip from semicolon on to new line\n\0"
So the for loop starts at r and stops at the first \0.
//Function of compatible fgets to read up to the character specified by a delimiter.
//However file stream keep going until to newline.
//s : buffer, n : buffer size
char *fgets_delim(char *s, int n, FILE *fp, char delimiter){
int i, ch=fgetc(fp);
if(EOF==ch)return NULL;
for(i=0;i<n-1;++i, ch=fgetc(fp)){
s[i] = ch;
if(ch == '\n'){
s[i+1]='\0';
break;
}
if(ch == EOF){
s[i]='\0';
break;
}
if(ch == delimiter){
s[i]='\0';//s[i]='\n';s[i+1]='\0'
while('\n'!=(ch = fgetc(fp)) && EOF !=ch);//skip
break;
}
}
if(i==n-1)
s[i] = '\0';
return s;
}
Given a requirement to use fgetc(), then you are probably supposed to echo everything up to the first semicolon on the line, and suppress everything from the semicolon to the end of the line. I note in passing that getc() is functionally equivalent to fgetc() and since this code is about to read from standard input and write to standard output, it would be reasonable to use getchar() and putchar(). But rules are rules...
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int c;
bool read_semicolon = false;
while ((c = fgetc(stdin)) != EOF)
{
if (c == '\n')
{
putchar(c);
read_semicolon = false;
}
else if (c == ';')
read_semicolon = true;
else if (read_semicolon == false)
putchar(c);
/* else suppressed because read_semicolon is true */
}
return 0;
}
If you don't have C99 and <stdbool.h>, you can use int, 0 and 1 in place of bool, false and true respectively. You can use else if (!read_semi_colon) if you prefer.
I am new to C programming and I am currently trying to teach myself how to create a C program that can count words and lines in the input stream and print the two totals to the standard output.
What I am actually trying to do is to have the program count the number of lines and count the number of words depending on the definition of a word in which I feel that I am off.
I want the words to exclude blanks, tabs, newlines, hyphens, or colons. While having the program output the results (words and lines) as decimals.
#include<stdio.h>
int main()
{
int iochar;
int words;
int lines;
printf("Enter something here:\n\n");
while ((iochar = getchar ()) !=EOF)
{
if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
putchar(iochar);
}
return 0;
}
Am I totally off on this program?
If your question is how to fix the compile error, that's simple. Add one more closing brace at the end.
But your program will still do only one pass through the loop and will print only one character if and only if the user types a space, tab or newline. No matter what the user types, the program will then terminate. I doubt that's what you wanted.
I suspect this is what you intended:
while ((iochar = getchar ()) !=EOF)
{
if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
{
putchar(iochar);
}
}
return 0;
After your "I am trying to have thee numbers be right justified in an 8-column field ..." I cannot understand what you are trying to say :(
int words = 0;
int lines = 0;
char buffer[1024];
while(fgets(buffer, sizeof buffer, stdin))
{
lines++;
if(buffer[0] == '\n')
continue;
char *tmp = buffer-1;
while(tmp = strchr(tmp+1, ' '))
words++;
words++; /* count last word before \0*/
}
printf("lines: %d, words: %d\n", lines, words);
is that what you need/want?
The error message is:
Test.c:20:1: error: expected declaration or statement at end of input
It does not compile because you are missing a }.
Had you properly indented your code, like so, you would have found your mistake:
#include<stdio.h>
int main() {
int iochar;
int words;
int lines;
printf("Enter something here:\n\n");
while ((iochar = getchar ()) !=EOF)
{
if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
{
putchar(iochar);
iochar = getchar();
}
return 0;
}
Yet another example of the importance of readability :)