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);
}
}
Related
I am writing a program to read a user input statement and extract all integers from the input. For example, if I enter "h3ll0", the program will output "30". I have used the fgets function to read the user input.
However, I am currently reading about getchar() and would like to know what would be the best way to use getchar() in my program to read user input instead of fgets. I am not really clear on how getchar() works and what situations it can be useful in.
This question is related to a project that specifically asks for getchar() as the method of reading user input. As I was unclear on how getchar() works, I built the rest of the program using fgets to ensure it was working.
#include <stdio.h>
int main()
{
char user_input[100];
int i;
int j = 0;
printf("Please enter your string: ");
fgets(user_input ,100, stdin);
for(i = 0; user_input[i] ; i++)
{
if(user_input[i] >= '0' && user_input[i] <= '9')
{
user_input[j] = user_input[i];
j++;
}
}
user_input[j] = '\0';
printf("Your output of only integers is: ");
printf("%s\n", user_input);
return 0;
}
OP: unclear on how getchar() works
int fgetc(FILE *stream) typically returns 1 of 257 different values.
"If ... a next character is present, the fgetc function obtains that character as an unsigned char converted to an int C11 §7.21.7.1 2
On end-of-file or input error (rare), EOF, is returned.
OP: to use getchar() in my program to read user input instead of fgets.
Create your own my_fgets() with the same function signature and same function as fgets() and then replace.
char *fgets(char * restrict s, int n, FILE * restrict stream);
The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array. C11 §7.21.7.2 2
Return the same value
The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned. §7.21.7.2 3
Sample untested code
#include <stdbool.h>
#include <stdio.h>
char *my_fgets(char * restrict s, int n, FILE * restrict stream) {
bool something_read = false;
int ch = 0;
char *dest = s;
// Room ("reads at most one less") and EOF not returned?
while (n > 1 && (ch = fgetc(stream)) != EOF) {
n--;
something_read = true;
*dest++ = (char) ch;
if (ch == '\n') {
break; // "No additional characters are read after a new-line character"
}
}
// Did code end the while loop due to EOF?
if (ch == EOF) {
// Was EOF due to end-of-file or rare input error?
if (feof(stream)) {
// "If end-of-file is encountered and no characters ... read into the array ..."
if (!something_read) {
return NULL;
}
} else {
// "If a read error ..."
return NULL; // ** Note 1
}
}
// room for \0?
if (n > 0) {
*dest = '\0'; //" A null character is written immediately after the last character"
}
return s;
}
Perhaps improve fgets() and use size_t for n.
char *my_fgets(char * restrict s, size_t n, FILE * restrict stream);
fgets() with n <= 0 is not clearly defined. Using size_t, an unsigned type, at least eliminates n < 0 concerns.
Note 1: or use s = NULL; instead of return NULL; and let the remaining code null terminate the buffer. We have that option as "array contents are indeterminate".
Something like this should work as a clunky replacement to fgets using only getchar. I don't guarantee the accuracy of the error handling.
I don't think you would ever want to use getchar over fgets in an application. Getchar is more limited and less secure.
#include <stdint.h>
void your_fgets(char *buffer, size_t buffer_size)
{
int i;
size_t j;
if (buffer_size == 0)
return ;
else if (buffer_size == 1)
{
buffer[0] = '\0';
return ;
}
j = 0;
while ((i = getchar()) != EOF)
{
buffer[j++] = i;
if (j == buffer_size - 1 || i == '\n')
{
buffer[j] = '\0';
return ;
}
}
buffer[j] = '\0';
}
I am baffled by the comments on this post suggesting that fgets is easier to use. Using fgets unnecessarily complicates the issue. Just do:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int c;
while( ( c = getchar() ) != EOF ) {
if(isdigit(c) && (putchar(c) == EOF)) {
perror("stdout");
return EXIT_FAILURE;
}
}
return ferror(stdin);
}
There is absolutely no reason to use any additional buffering, or read the input one line at a time. Maybe you'll want to output newlines as they come in, but that would be an implementation detail that is left unspecified in the question. Either way, it's utterly trivial (if(( c == '\n' || isdigit(c)) && (putchar(c) == EOF))). Just read a character and decide if you want to output it. The logic is much easier if you don't think about the input as being more complicated than it is. (It's not line-oriented...it's just a stream of bytes.)
If, for some unknown reason you want to make this tool usable only in an interactive setting and load up your output with excess verbosity, you can easily do something like:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int c;
do {
int want_header = 1;
printf("Please enter your string: ");
while( ( c = getchar() ) != EOF && c != '\n' ) {
if(! isdigit(c)) {
continue;
}
if(want_header) {
want_header=0;
printf("Your output of only integers is: ");
}
if(putchar(c) == EOF) {
perror("stdout");
return EXIT_FAILURE;
}
}
if( c == '\n')
putchar(c);
want_header = 0;
} while(c == '\n');
return ferror(stdin);
}
but, please, don't do that. (Imagine if grep started by emitting a prompt that said "please enter the regex you would like to search for"!)
I am writing a program that copies input to output character by character on Linux terminal. The code is as follows (from Dennis Ritchie's C book)
#include <stdio.h>
/* copy input to output; 2nd version*/
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
The program and its execution works fine. But I want a slight modification.
The output appears on terminal for each new line character (when I press enter). I want to delay the output till I signal the end of file by pressing Ctrl + D. What modifications I have to do for the program in-order to delay my output on terminal.
Sample output I am getting is as follows:
abcd (enter)
abcd
llefn;elnf(enter)
llefn;elnf
(ctrl+d)
Sample output I wants to get is as follows:
abcd(enter)
llefn;elnf(ctrl+d)
abcd
llefn;elnf
You need to store these character's to buffer, control indexes where are you writing and when you receive EOF just print that buffer via printf.
If you cant solve it you can inspire here
#include <stdio.h>
#define BUFFER_SIZE 1024
int main()
{
int c, i = 0;
char buffer[BUFFER_SIZE];
while ((c = getchar()) != EOF)
{
if (i < BUFFER_SIZE - 1)
{
buffer[i] = c;
i++;
}
else
{
buffer[BUFFER_SIZE - 1] = '\0';
printf("%s", buffer);
i = 0;
}
}
buffer[i] = '\0';
printf("%s", buffer);
return 0;
}
An easy, albeit sloppy and partial solution is to configure stdout to fully buffered with a large buffer:
#include <stdio.h>
int main(void) {
int c;
setvbuf(stdout, NULL, _IOFBF, 32767);
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
Notes:
On a 32- or 64-bit system, you could make the buffer ridiculously large.
Passing NULL to setvbuf lets it allocate the buffer with malloc().
As already mentioned in the comments: put the characters into a buffer and display the whole buffer at the end:
#include <stdio.h>
#define BUF_SIZE 1024
int main()
{
char str[BUF_SIZE]; // the buffer
int c, i = 0;
while (i < BUF_SIZE-1 && (c = getchar()) != EOF)
str[i++] = (char) c;
str[i] = '\0';
printf("%s\n", str); // display the contents of the buffer
}
You could set buffer to stdout with setvbuf(3).
#include <stdio.h>
main()
{
int c;
char buf[BUFSIZ];
setvbuf(stdout,buf,_IOFBF,BUFSIZ);
while ((c=getchar())!=EOF)
putchar(c);
}
The key here is the fully buffered mode specified with the _IOFBF constant.
The size of the buffer is set to BUFSIZ which usually equals 8192.
As was correctly pointed in the comments by Jonathan Leffler the limited size of the buffer may cause the program to suddenly spit out its contents garbling the terminal. To avoid that one could track the utilization of the buffer and extend its size when it gets filled.
I have 2 C functions that interact with one another. The first a writer function takes an int n and writes "Hellohello" n number of times. The reader function reads whatever is input to it, and every 50 characters inserts a newline character.
My current dilemma is that when I have a number of characters that is a factor of 50 my reader is putting an extra newline character in when I do not want it to. I have tried multiple different ways to remedy this and nothing I have attempted has worked as of yet. What I'm providing is my reader code without any of my attempted fixes as well as an example of what the problem is.
I do have to use getchar and putchar, I understand that there would be easier ways if I wasn't using them but it is unfortunately a must. Any assistance as to how I should approach this or something I should have thought about are greatly appreciated.
reader code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
char c;
while (c != EOF)
{
c = getchar();
if (count == 50)
{
putchar('\n');
count = 0;
}
putchar(c);
count++;
}
}
example output:
[88] [cbutc1#courses2016:~/csc412]$ writer 10 | reader1
HellohelloHellohelloHellohelloHellohelloHellohello
HellohelloHellohelloHellohelloHellohelloHellohello
▒[89] [cbutc1#courses2016:~/csc412]$
edit: clarity
When you read (getchar) a newline you print a newline (putchar).
Also, 'c' should be declared 'int'' so it is big enough to hold EOF properly.
Also the value of 'c' is undefined the first time through the loop and you print "EOF'", use:
while ((c = getchar()) != EOF) { …
Additionally, you should use int main ( void ) { …
And the C language does have "classes", only functions.
Simply changed the if statement that was checking the count to include a check for newline characters. This remedied the problem that was occuring.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
char c;
while (c != EOF)
{
c = getchar();
if ((count == 50) && (c != '\n'))
{
putchar('\n');
count = 0;
}
putchar(c);
count++;
}
}
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.
Consider the following code:-
#include"stdio.h"
void main()
{
char ch;
while((ch=getchar())!=EOF)
{
putchar(ch);
}
}
Whatever input I give to (as a sentence) it is repeated after I hit return key. What should I do if I want to get the entire paragraph at the end ? Can this be done using putchar() because putchar() can be used only to return a single character.
This won't work, since EOF doesn't fit in a char. Note that the proper return type of getchar() is int. See for instance this manual page.
If you want to read in a whole line at once, you can use fgets() into a character buffer for instance. I'm not sure I'm understanding exactly what you want to achieve, though.
EOF should be used when reading from files as the files end with a special EOF(end of file) character.You need to use any sentinel here to represent end of input.
this program makes a very little sense and I cant picture the use of this anywhere. So rethink about the requirements and change the logic accordingly.
may this code help you
char *buffer;
int i = 255;
buffer = (char *)malloc(i*sizeof(char));
*buffer = getchar();
while ( *buffer != '?' )
{
buffer++;
*buffer = getchar();
}
Try to store your char into a buffer and the when quit the while loop print the buffer. Try this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int c;
char *buf = calloc(1,sizeof(char));
int len;
while ((c=getchar())!=EOF) {
len = strlen(buf);
buf = realloc(buf, len+1);
buf[len] = (char) c;
buf[len + 1] = '\0';
}
printf("%s",buf);
}
If you want to get entire paragraph at end, you should store the input in a buffer while EOF reaches. then print content of buffer in a loop. Also as Mr. Unwind's answer says make, ch variable a int, char is wrong!
#include"stdio.h"
#define SIZE 1024
void main()
{
int buffer[SIZE]
int ch;
int i=0;
// Read and store in a buffer
while((ch=getchar())!=EOF)
{
buffer[i] = ch;
i++;
}
buffer[i] = EOF;
// now print using putchar(ch);
i = 0;
while((ch = buffer[i]) !=EOF)
{
putchar(ch);
i++;
}
}
cose all we did in console/terminal - until we dont hit Enter/Return/^J/^M shell not send line to our program
u can get paragraph(more then 1 line) by copy and paste some lines so terminal|console program show 1st u pasted then repeated - output of u program