我尝试在我的C程序多行输入表单stdin中使用带有此代码的换行符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#define DEFAULT_INPUT_LENGTH 20
char * readMessage(FILE* file);
void writeChar(char* string, char c);
int main()
{
printf("Message:\n");
char * msg = readMessage(stdin);
printf("Input: %s\n", msg);
free(msg);
return 0;
};
char * readMessage(FILE* file)
{
char *input = malloc(DEFAULT_INPUT_LENGTH);
int inputCounter = 0;
int n = 1;
char c;
while(!feof(stdin))
{
c=fgetc(file);
inputCounter++;
if (inputCounter == DEFAULT_INPUT_LENGTH * n)
{
n++;
int chars = DEFAULT_INPUT_LENGTH * n;
input = realloc(input, chars);
}
writeChar(input, c);
}
return input;
}
void writeChar(char* in, char c)
{
int i;
for(i = 0; ; i++)
{
if (in[i] == '\0')
{
in[i] = c;
break;
}
}
}
但是当我在Linux上尝试CTRL + D或在Windows中尝试CTRL + Z时输入没有结束。
输入示例如下:
asfer
dfdfd
sffdfl
在这个例子中如果我在最后一个char之后尝试CTRl + D输入未结束我必须使用enter和CTRL + D
答案 0 :(得分:1)
试试这个
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_INPUT_LENGTH 20
char * readMessage(FILE* file);
void writeChar(char* string, char c);
int main(void){
printf("Message:\n");
char * msg = readMessage(stdin);
printf("Input: %s\n", msg);
free(msg);
return 0;
}
char * readMessage(FILE* file){
char *input = malloc(DEFAULT_INPUT_LENGTH);
int inputCounter = 0;
int n = 1;
int c;//!
*input = 0;//!
while((c=fgetc(file)) != EOF){//!
inputCounter++;
if (inputCounter == DEFAULT_INPUT_LENGTH * n){
n++;
int chars = DEFAULT_INPUT_LENGTH * n;
input = realloc(input, chars);
}
writeChar(input, c);
}
return input;
}
void writeChar(char* in, char c){
int i;
for(i = 0; ; i++){
if (in[i] == '\0'){
in[i] = c;
in[i+1] = 0;//!
break;
}
}
}