hi I would like to ask how I would modify this code for the question: (It only accepts one input then prints it out. I want it to keep going until I hit enter (\n) twice.
#include <stdio.h>
#define MAXLENGTH 1000
int main(void) {
char string[MAXLENGTH];
fgets(string, MAXLENGTH, stdin );
printf("%s\n", string);
return 0;
}
I'm confused at the fgets(string, MAXLENGTH, stdin ); line, what does stdin mean/do?
EDIT: Chris, I've tried your way:
#include <stdio.h>
#define MAXLENGTH 1000
int main(void) {
char string[MAXLENGTH];
do {
if (!fgets(string, MAXLENGTH, stdin ))
break;
printf("%s", string);
}
} while (string[0] != '\n')开发者_如何学编程;
return 0;
}
It prints after i hit enter but i want to type the whole list first then allow it to print the list after I press enter twice.
Try this:
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 1000
int main(void)
{
char string[MAXLENGTH];
int i = 0;
for(;;++i)
{
string[i] = getchar();
if (i > 0 && string[i] == '\n' && string[i-1] == '\n') break;
}
string[i] = 0;
printf("Print it again:\n%s",string);
return 0;
}
do {
if (!fgets(string, MAXLENGTH, stdin ))
break;
printf("%s", string);
} while (string[0] != '\n');
will keep reading input and printing it until it sees a blank line (hitting enter twice in a row) or until EOF.
stdin
refers to the program's standard input, which is whatever input source it is connected to when you run it. If you're just running it at the command line with no extra shell redirections, that will be the keyboard.
If you want to make entire input to be printed after the return key is pressed twice you can do:
char string[MAXLENGTH]; // to hold a single input line.
char strings[MAXLENGTH]=""; // to hold the entire input lines.
do {
if (fgets(string, MAXLENGTH, stdin ) == NULL)
break;
strcat(strings,string);
} while (string[0] != '\n');
printf("%s", strings);
精彩评论