C 反转字符直到EOF
我正在创建一个程序,使用C 反转字符直到EOF,c,eof,C,Eof,我正在创建一个程序,使用getchar反转行(每个字符)。 这就是我到目前为止得到的(我的代码有点混乱,因为我是初学者) #包括 #定义MAX_CH 256 内部主(空) { int ch=0; int i=0; int字符串[MAX_CH]={0}; 而(ch!='\n') { ch=getchar(); 字符串[i]=ch; ++一,; } i=i-2;//将i放回最后一个字符的位置 int极限=i; int n; int reverse[MAX_CH]={0}; 对于(n=0;n可以使用如
getchar
反转行(每个字符)。
这就是我到目前为止得到的(我的代码有点混乱,因为我是初学者)
#包括
#定义MAX_CH 256
内部主(空)
{
int ch=0;
int i=0;
int字符串[MAX_CH]={0};
而(ch!='\n')
{
ch=getchar();
字符串[i]=ch;
++一,;
}
i=i-2;//将i放回最后一个字符的位置
int极限=i;
int n;
int reverse[MAX_CH]={0};
对于(n=0;n可以使用如下循环:
do {
i=0;
while ((ch=getchar())!=EOF && ch!='\n') {
string[i++] = ch;
}
string[i] = '\0'; // terminate it
for (int j=0, i--; j<i; j++, i--) { // reverse line
char tmp= string[j];
string[j]= string[i];
string[i]= tmp;
}
} while (ch != EOF);
do{
i=0;
而((ch=getchar())!=EOF&&ch!='\n'){
字符串[i++]=ch;
}
字符串[i]='\0';//终止它
对于(intj=0,i--;j,这里有一个更通用的版本。从文件或stdin读取支持的任何行长度(至少在realloc失败之前)
char*reverse(char*str)
{
尺寸长度=strlen(str);
用于(大小\u t pos=0;pos
只要可以读取输入行,就要重复代码
这里有几个问题需要解决
- 数组不需要有
int
类型,char
类型是更合适的选择
- 在反转的行之后输出一个换行符
- 您不需要单独的数组来存储反转的行,只需从
字符串
数组中以相反的顺序打印字符即可
- 为了简单起见,您可以使用
putchar
而不是printf
以下是修改后的版本:
#include <stdio.h>
#define MAX_CH 256
int main(void) {
int ch, i, length;
char string[MAX_CH];
for (;;) {
for (i = 0; i < MAX_CH; i++) {
if ((ch = getchar()) == EOF || (ch == '\n'))
break;
string[i] = ch;
}
length = i;
if (length == 0) {
/* no character read => EOF */
break;
}
for (i = 0; i < length; i++) {
putchar(string[length - i - 1]);
}
putchar('\n');
}
return 0;
}
#包括
#定义MAX_CH 256
内部主(空){
int ch,i,长度;
字符字符串[MAX_CH];
对于(;;){
对于(i=0;iEOF*/
打破
}
对于(i=0;i
在while(ch!='\n')
块之外,或者下面的所有代码也会反转行?您需要发布不起作用的代码。第一个循环实际上需要三个条件:i
和ch!='\n'
和ch!=EOF
注意:while((ch=getchar())!=EOF&&ch!='\n'){string[i++]=ch;}
类似于使用gets()
。两者都缺乏缓冲区溢出保护。
char *reverse(char *str)
{
size_t len = strlen(str);
for (size_t pos = 0; pos < len / 2; pos++)
{
char tmp = str[pos];
str[pos] = str[len - 1 - pos];
str[len - 1 - pos] = tmp;
}
return str;
}
#define MEMINC 80
int PrintReversedLines(char *filename)
{
FILE *fi = !strcmp(filename, "stdin") ? stdin : fopen(filename, "rt");
char *tmpbuff = NULL, *buff = NULL;
size_t pos = 0;
int ch = 0;
if (!fi) return -1;
while ((ch = fgetc(fi)) != EOF)
{
if (!(pos % MEMINC))
{
if (!(tmpbuff = realloc(buff, pos + 80)))
{
if (buff) free(buff);
return -1;
}
else
{
buff = tmpbuff;
}
}
if (ch == '\r') continue;
if (ch == '\n')
{
buff[pos++] = 0;
printf("%s\n", reverse(buff));
free(buff);
buff = NULL;
pos = 0;
}
else
{
buff[pos++] = ch;
}
}
return 0;
}
int main()
{
PrintReversedLines("stdin");
}
#include <stdio.h>
#define MAX_CH 256
int main(void) {
int ch, i, length;
char string[MAX_CH];
for (;;) {
for (i = 0; i < MAX_CH; i++) {
if ((ch = getchar()) == EOF || (ch == '\n'))
break;
string[i] = ch;
}
length = i;
if (length == 0) {
/* no character read => EOF */
break;
}
for (i = 0; i < length; i++) {
putchar(string[length - i - 1]);
}
putchar('\n');
}
return 0;
}