[英]What changes do I have to make to my code so it also sorts negative numbers?
[英]What do I have to change in my code to get the right result?
我怎樣才能得到我想要的結果?
我的代碼反轉文件和文件的每一行,並在行前打印一個數字。但在我的代碼中,這不能正常工作。 例子:
test.txt :
alma
barack
szilva
Result:
3 avlizs
2 kcarab
1 amla
我的問題是我得到了這個結果:
只有 3 個數字,但我也需要 1 和 2。
3 avlizs
kcarab
amla
我必須對代碼進行哪些更改才能正常工作?
#ifndef REVERSE_H
#define REVERSE_H
void reverse( FILE *fp, char *name);
#endif /* REVERSE_H */
#include <stdio.h>
#include "reverse.h"
int main( int argc, char *argv[])
{
if ( argc < 2 )
{
reverse( stdin, "stdin"); /* stdin */
}
else
{
int i;
for ( i = 1; i < argc; ++i ) /* fájlnevek */
{
FILE *fp = fopen( argv[i], "r");
if ( NULL != fp )
{
reverse( fp, argv[i]); /* fp-ről olvas */
fclose(fp);
}
else
{
fprintf(stderr,"Can't open %s for read\n",argv[i]);
}
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "reverse.h"
#define INITCAP 4
#define BUFSIZE 1024
char **read( FILE *fp, int *pLines);
void write( char **lines, int nLines, char *name);
void revline( char *line);
void memoria( void *ptr);
void reverse( FILE *fp, char *name)
{
int nLines = 0;
char **lines = read( fp, &nLines);
write( lines, nLines, name);
}
char **read( FILE *fp, int *pLines)
{
int capacity = INITCAP;
int nLines = 0;
char buffer[BUFSIZE];
char **lines = (char **)malloc(capacity * sizeof(char*));
memoria(lines);
while ( NULL != fgets(buffer, BUFSIZE, fp) )
{
int len = strlen(buffer);
if ( '\n' == buffer[len-1] )
{
buffer[len-1] = '\0';
}
if ( nLines == capacity )
{
capacity *= 2;
lines = realloc( lines, capacity * sizeof(char *));
memoria(lines);
}
lines[nLines] = (char *) malloc(len+1);
memoria(lines[nLines]);
strcpy( lines[nLines], buffer);
++nLines;
}
*pLines = nLines;
return lines;
}
void write( char **lines, int nLines, char *name)
{
for (int i = nLines-1; i >= 0; --i)
{
char *curr = lines[i];
fprintf( stdout, " %d " , i+1 );
revline(curr);
free( curr);
}
free(lines);
}
void revline( char *line)
{
int len = strlen(line);
while ( --len >= 0 )
{
fputc( line[len], stdout);
}
fputc( '\n', stdout);
}
void memoria( void *ptr)
{
if ( 0 == ptr )
{
fprintf( stderr, "Memory allocation failed!\n");
exit(1);
}
}
我猜您的文本文件是在 Windows 上生成的,帶有\r\n
行尾,並且您的程序在 UNIX 上運行。 如果是這種情況, fopen(..., "r")
調用不會將這些行尾轉換為\n
(它會在 Windows 上完成)並且當您剝離該行的最后一個\n
時, \r
留在最后。 顯示這樣的一行將跳轉到左邊距並覆蓋之前寫入的數字。
我建議這種剝離,只是為了確定
while ( len && ('\n' == buffer[len-1] || '\r' == buffer[len-1]) )
{
buffer[--len] = '\0';
}
但這只是猜測...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.