Write a program that will read standard input and echo each line to standard output with a line number and tab preceding it. When you run this program and enter lines from the terminal, lines of input will be interspersed with lines of output. If your system has output redirection and you redirect output to a file, the file will look like the input with the lines numbered.
Here is an example of how the script should work.
User input in bold.
Enter your text:
This is line 1.
1 This is line 1.
This is line 2.
2 This is line 2.
This is the last line of input.
3 This is the last line of input.
The last line will end the process.
Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Enter your text: \n");
while (1)
{
int ch = getc(stdin);
fflush(stdout);
if(ch == EOF) break;
putc(ch, stdout);
}
return 0;
}
I have been attempting at this for a few hours now to no luck, any help is appreciated. I basically cant get my script to display the example output. I can get my script to display the stdin as an stdout and thats all. This is a C assignment.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void){
size_t no = 0;
bool line_top = true;
printf("Enter your text: \n");
while (1) {
int ch = fgetc(stdin);
if(ch == EOF) break;
if(line_top)
printf("%zu ", ++no);
line_top = (ch == '\n');
fputc(ch, stdout);
}
fflush(stdout);
return 0;
}
To properly complete the assignment, you need to understand what is the line. The code you have in place reads and prints data symbol-by-symbol. This is not going to print the numbers requested!
There are two solutions here. First is to switch from reading symbol by symbol to line by line, and than print an ever incrementing counter every time you print a line. Second is leave reading symbol-by-symbol, but print an incremented number every time you've read a new line symbol from the input. A slight challenge here is that you would need a state - that is, once you've seen the new line character, you should remember that fact, but not print the number right away - this might be the last line in the input. Instead, print a number whenever your saved state tells you so, and reset the flag after this.
A separate question is what to do with the empty lines - do they participate in counter increment or not - but this is probably beyond the assignment.
Ok you should only do what the assignment requires. Here's the most straight-forward solution I can think of:
#include <stdio.h>
int main(void)
{
char buf[1024];
int num = 0;
/* read a line as long as we can read (no error / EOF) */
while (fgets(buf, 1024, stdin))
{
/* print line number */
printf("%d\t", ++num);
/* print what we actually read */
fputs(buf, stdout);
}
return 0;
}
Test run:
> ./numlines < numlines.c
1 #include <stdio.h>
2
3 int main(void)
4 {
5 char buf[1024];
6 int num = 0;
7
8 /* read a line as long as we can read (no error / EOF) */
9 while (fgets(buf, 1024, stdin))
10 {
11 /* print line number */
12 printf("%d\t", ++num);
13
14 /* print what we actually read */
15 fputs(buf, stdout);
16 }
17
18 return 0;
19 }
20
Code needs to keep track of the beginning of a line. This can be done by reading a line using fgets() or by looking at individual char.
fgets() is likely faster, but it limits line length to some constant.
fgetc() gets 1 unsigned char at a time (or EOF).
The below follows OP's lead, yet adds the inner while loop.
Not much code needed.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned long long line_number = 0;
int ch;
while ((ch = fgetc(stdin)) != EOF) {
printf("%llu\t", ++line_number);
while (ch != EOF && fputc(ch, stdout) != '\n') {
ch = fgetc(stdin);
}
}
return 0;
}
const int buflen = 1024;
char buffer[buflen];
int count = 0;
while (1)
{
char* line = fgets(buffer, buflen, stdin);
if (line == null)
break;
fprintf(stdout, "%d: %s\n", ++count, line);
}
Here's a c++ solution using getline and cout.
#include <string>
#include <iostream>
using namespace std;
int main()
{
unsigned int i=0;
string s;
cout<<"Enter your text: "<<endl;
while (std::getline(cin,s))
{
cout<<++i<<'\t'<<s<<endl;
}
return 0;
}
Here a c solution:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int exit=0, i=0, newline=1;
printf("Enter your text: \n");
while (!exit)
{
int ch = getc(stdin);
if(newline){
printf("\n%d\t",++i);
newline=0;
}
switch(ch){
case '\n':
newline=1;
printf("\n");
break;
case EOF:
printf("\n");
exit=1;
break;
default:
printf("%c",(char)ch);
break;
}
}
return 0;
}
#include<stdio.h>
int main()
{
char line[1000];
int lineno=0;
while((fgets(line,1000, stdin)) != NULL)
{
lineno++;
printf("%d ",lineno);
fputs(line, stdout);
}
}
It will work as you are expected. It is a simple method to do this. You don't have to put the while(1) and if condition and break the loop.
Related
QUESTION:
What is wrong with this code example, what is missing?
Current incorrect output is:
There are 0 words in ""
Code Explanation:
Write a program that reads in a line of text, and prints out the number of words in that line of text. A word contains characters that are alphanumeric. Hint: Use the fgets() function.
Sample run:
Input:
from here to eternity
Output:
4
Input:
start here and turn 180 degrees
Output:
6
Code Snippet:
https://onlinegdb.com/H1rBwB83V
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#define MAXLEN 100
int countWords(char str[])
{
int i=0;
int count = 0;
bool flag = false;
while (str[i] != '\0')
{
if (isalnum(str[i]))
{
if (!flag)
{
count++;
flag = true;
}
}
else
flag = false;
i++;
}
return count;
}
int main(int argc, char **argv) {
char str[MAXLEN];
int count;
while (fgets(str, sizeof(str), stdin) != NULL)
{
str[strlen(str-1)] = '\0'; // the last character is the newline. replace with null
count = countWords(str);
printf("There are %d words in \"%s\"\n", count, str);
}
return 0;
}
Similar Tutorial:
https://www.sanfoundry.com/c-program-count-words-in-sentence/
You have an error here:
str[strlen (str - 1)] = '\0'; // the last character is the newline. replace with null
Using the pointer str - 1 leads to undefined behavior, as it points to memory outside the original string.
You actually meant to do this: strlen(str) - 1 (notice the -1 is moved outside the parentheses)
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 256
int main(int argc, const char * argv[]) {
char testo[N];
int i;
printf("PER TERMINARE L'INSERIMENTO PREMERE CTRL+Z oppure CTRL+D \n");
for(i=0;i<N;i++)
{
scanf("%c",&testo[i]);
/* if(testo[i]=='h' && testo[i-1]=='c')
{
i--;
testo[i]='k';
}
if(testo[i]==testo[i-1])
{
i--;
} */
if(testo[i]==EOF)
{
break;
}
}
puts(testo);
return 0;
}
When the code in /* ... */ is compiled, I can't stop the insert of text with EOF, but when the code is built and run as shown here, the EOF works.
Does anyone have any idea what the problem is?
You're testing for EOF incorrectly. With scanf(), you need to look at the return value. In fact, with almost all input functions, you need to test, if not capture and test, the return value.
Superficially, you need:
for (i = 0; i < N; i++)
{
if (scanf("%c", &testo[i]) == EOF)
break;
…
}
However, in general, you should check that scanf() made as many successful conversions as you requested, so it is better to write:
for (i = 0; i < N; i++)
{
if (scanf("%c", &testo[i]) != 1)
break;
…
}
In this example, it really won't matter. If you were reading numeric data, though, it would matter. The user might type Z instead of a number, and scanf() would return 0, not EOF.
To detect EOF, check the result of scanf()
if scanf("%c",&testo[i]) == EOF) break;
Note: testo[] may not be null character terminated. To print as a string, insure it is.
char testo[N];
int i;
// for(i=0;i<N;i++) {
for(i=0;i<(N-1);i++) {
if (scanf("%c",&testo[i]) == EOF) break;
}
testo[i] = '\0'; // add
puts(testo);
To stop at end of file, check the return value from scanf:
scanf returns the number of inputs correctly parsed. In your case, %c reads a byte from the stream correctly as long as end of file has not been reached. if (scanf("%c",&testo[i]) != 1) break; will do.
Yet using scanf to read one byte at a time from the input stream is overkill. The idiomatic way to do this in C is using the getchar() or the getc() function. The return value must be stored in an int variable and has special value EOF upon end of file.
You should also make the array 1 byte longer and store a null byte at the end to make it a C string, as expected by puts.
Here is a modified version of your program:
int main(int argc, const char *argv[]) {
char testo[N+1];
int i;
printf("PER TERMINARE L'INSERIMENTO PREMERE CTRL+Z oppure CTRL+D\n");
for (i = 0; i < N; i++) {
int c = getchar();
if (c == EOF)
break;
testo[i] = c;
/* ... further processing ... */
}
testo[i] = '\0';
puts(testo);
return 0;
}
I'm trying to create program in C that reads user input. Correct user input is [number][space][number]. I read every input char and check if there was exactly one space. When comes '\n' I need all input chars were stored in the array. The problem is that I know size of array only when '\n' comes. How can I write input to array?
Here is my code:
#include <stdlib.h>
#include <stdio.h>
int array_size=0;
char input;
int spaces=0;
int main (){
while ((input = getchar())!=EOF){
array_size++;
if(input==' '){ //if user input a space
spaces++;
}
if(spaces>1){
fprintf(stderr, "You can input only one space in row\n");
spaces=0;
array_size=0;
continue;
}
if(input=='\n'){ //if thre is only one space and user inputs ENTER
char content[array_size+1];
//here I know array size and need to add to array all chars that were inputed
content[array_size-1]=='\0'; //content is a string
if((content[0]==' ')||(content[array_size-2]==' ')){
fprintf(stderr, "You can't input space only between numbers\n");
spaces=0;
array_size=0;
continue;
}
//then work with array
spaces=0;
array_size=0;
}
}
exit(0);
}
Your code is broken. Here is an example. Take it as a starting point.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void) {
char input[10]; // 10 is just an example size
int c; // current character read
int token_no = 0;
// we read until EOF
while ((c = getchar()) != EOF) { //read chars while EOF
if(c == '\n') // or newline
break;
if (token_no % 2 == 0) { // if no of token is even, then we expect a number
if (isdigit(c)) {
input[token_no++] = c;
} else {
printf("Expected number, exiting...\n");
return -1;
}
} else {
if (c == ' ') {
input[token_no++] = c;
} else {
printf("Expected space, exiting...\n");
return -1;
}
}
}
input[token_no++] = '\0'; // here you had ==, which was wrong
printf("%s\n", input);
return 0;
}
Output1:
1 2 3
1 2 3
Output2:
123
Expected space, exiting...
Output3:
1 <- I have typed two spaces here
Expected number, exiting...
If you want to dynamically allocate and array, use malloc after determining the size
int *a = (int*)malloc(sizeof(int) * size)
or take a look a these answeres:
can size of array be determined at run time in c?
How to declare the size of an array at runtime in C?
I am trying to master working with files in C, and I have a bump which I can't pass. I have been searching all day for information but I can't seem to find what I am looking for. I would like to number the lines in a file. For example, if I type in information about a book (let's say: Name, Air-date and id), I would expect something like this in my file:
1. Name:Dave Air-Date:1997 id:123
And I would like this to update itself. Say I close the program and run it again, the counting should start from 2.
My only problem is numbering the lines. Could someone point me in the right direction how to do this, or show me a sample source code?
You could process each character one by one, and increment a counter that you print before the character when you encounter a carriage return (\n).
In pseudo-code:
lineNumber = 1;
Open the file
While ((c = read a character) is not EOF)
If (c is \n)
Print "lineNumber", then increment it
Print c
End while
Close the file
It's too late, but I hope it helps.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
/* user input */
char text[50];
char res[100] = "";
printf("Enter a short story (<100 characters): ");
char ch;
char *ptr = text;
while ((ch = getchar()) != EOF) {
*ptr++ = ch;
}
printf("\nYou've entered this text:\n");
printf("%s\n", text);
/* append and create a new text */
strcat(res, "0: ");
char *qtr = text;
int i = 1;
while (*qtr != '\0') {
if (*qtr != '\n') {
char temp[2];
sprintf(temp, "%c", *qtr);
strcat(res, temp);
} else {
char temp[5];
sprintf(temp, "\n%d: ", i++);
strcat(res, temp);
}
qtr++;
}
printf("\nLine number added: \n");
printf("%s\n", res);
return 0;
}
Im a beginner learning The C Programming language and using Microsoft visual C++ to write and test code.
Below program in C from text(section 1.5.1) copy its input to its output through putchar() and getchar():
#include <stdio.h>
int main(void)
{ int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;}
The program print characters entered by keyboard every time pressing ENTER.As a result,I can only enter one line before printing. I can't find a way to enter multi-line text by keyboard before printing.
Is there any way and how to let this program input and output multi-line text from keyboard?
Sorry if this is a basic and ignorant question.
Appreciate your attention and thanks in advance.
Some clever use of pointer arithmetic to do what you want:
#include <stdio.h> /* this is for printf and fgets */
#include <string.h> /* this is for strcpy and strlen */
#define SIZE 255 /* using something like SIZE is nicer than just magic numbers */
int main()
{
char input_buffer[SIZE]; /* this will take user input */
char output_buffer[SIZE * 4]; /* as we will be storing multiple lines let's make this big enough */
int offset = 0; /* we will be storing the input at different offsets in the output buffer */
/* NULL is for error checking, if user enters only a new line, input is terminated */
while(fgets(input_buffer, SIZE, stdin) != NULL && input_buffer[0] != '\n')
{
strcpy(output_buffer + offset, input_buffer); /* copy input at offset into output */
offset += strlen(input_buffer); /* advance the offset by the length of the string */
}
printf("%s", output_buffer); /* print our input */
return 0;
}
And this is how I use it:
$ ./a.out
adas
asdasdsa
adsa
adas
asdasdsa
adsa
Everything is parroted back :)
I've used fgets, strcpy and strlen. Do look those up as they are very useful functions (and fgets is the recommended way to take user input).
Here as soon as you type '+' and press enter all the data you entered till then is printed. You can increase the size of array more then 100
#include <stdio.h>
int main(void)
{ int c='\0';
char ch[100];
int i=0;
while (c != EOF){
c = getchar();
ch[i]=c;
i++;
if(c=='+'){
for(int j=0;j<i;j++){
printf("%c",ch[j]);
}
}
}
return 0;
}
You can put a condition on '+' char or whatever character you would like to represent print action so that this character is not stored in the array ( I have not put any such condition on '+' right now)
Use setbuffer() to make stdout fully buffered (up to the size of the buffer).
#include <stdio.h>
#define BUFSIZE 8192
#define LINES 3
char buf[BUFSIZE];
int main(void)
{ int c;
int lines = 0;
setbuffer(stdout, buf, sizeof(buf));
while ((c = getchar()) != EOF) {
lines += (c == '\n');
putchar(c);
if (lines == LINES) {
fflush(stdout);
lines = 0;
}}
return 0;}
Could you use the GetKeyState function to check if the SHIFT key is held down as you press enter? That was you could enter multiple lines by using SHIFT/ENTER and send the whole thing using the plain ENTER key. Something like:
#include <stdio.h>
int main(void)
{ int c;
while (true){
c = getChar();
if (c == EOF && GetKeyState(VK_LSHIFT) {
putchar("\n");
continue;
else if(c == EOF) break;
else {
putchar(c);
}
}