我想從命令行讀入憲法中的文本文件到我的程序中,以相反的順序打印出行。我的for循環如下所示:從相反順序的文本文件中打印行
for(int i = 0; i >= 0; i--) {
if(strings[i] == '\0') //counts through array until it finds a line break
{
break;
}
printf("%s", strings[i]);
}
程序運行時,唯一打印的是憲法的第一行。如果我修改我的for循環以增加i,程序運行順利並像正常一樣輸出憲法,因此我相信我的整個問題總結在此for循環中。這是我的程序的其餘部分供參考。
int clearBuffer() {
char junk;
while((junk = getchar()) != feof(stdin) && junk != '\n');
return 0;
}
int getAline(char ** bufferPointer, int * sizePointer){
char * buffer = *bufferPointer;
int count = 0;
int size = *sizePointer;
while(!feof(stdin)){
if(count >= size - 1){
char * tempBuffer = (char *)malloc(size * 10);
//strcpy(tempBuffer, buffer);
for (int i = 0; i < size; i++){
tempBuffer[i] = buffer[i];
//putchar(tempBuffer[i]);
}
free(buffer);
buffer = tempBuffer;
size *= 10;
}
buffer[count] = getchar();
if(buffer[count] == '\n'){
break;
}
if(buffer[count] == EOF){
buffer[count] = '\0';
break;
}
count++;
}
*bufferPointer = buffer;
*sizePointer = size;
return count-1;
}
int main(){
char * buffer;
char * strings[1000];
int arrayCount =0;
int size = 10;
while(!feof(stdin))
{
buffer= (char*) malloc(size);
getAline(&buffer, &size);
strings[arrayCount++] = buffer;
}
for(int i = 0; i >= 0; i--) {
if(strings[i] == '\0'){
break;
}
printf("%s", strings[i]);
}
return 0;
}
'for(int i = 0; i> = 0; i--){'only only。從最後一個號碼開始。 – BLUEPIXY
http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong –
'EOF'不是一個字符。 – melpomene