C代码在Linux编译器中不起作用

问题描述 投票:-3回答:1

下面的代码是关于C中的文件操作。

第一个程序读取文件并将其存储到数组后,该程序向用户询问您希望从文件中找到哪个问题。如果用户输入,“2”程序从文件中获取第二个问题(在文件中取2到3个数字之间的所有字符)并打印到屏幕上。

我在Windows中的DEV C ++编译器中编写了此代码。它在Dev C ++中工作。

但是当我在Linux终端中尝试此代码时,代码会向用户询问整数,但不会将结果从文件打印到屏幕。它不会给出任何错误并且程序关闭。

FILE* file = fopen("txt", "r"); 
char line[256];
char a[10][14];
char getIndex[2];
char firstIndex[2];
char secondIndex[2];
int firstIndexNum;
int secondIndexNum;

printf("Please enter number:");
fgets (getIndex, 100, stdin);
strcpy(firstIndex,getIndex);

firstIndexNum = atoi(firstIndex);

secondIndexNum = firstIndexNum + 1;

sprintf(secondIndex, "%d", secondIndexNum);


int i = 0;
while (fgets(line, sizeof(line), file)) {
    strcpy(a[i],line);
    i++;
}
int sizeArray = sizeof(a) / sizeof(a[0]);
for(int i=1;i<=sizeArray;i++){
    if(strstr(a[i-1], firstIndex) != NULL){
        while(strstr(a[i], secondIndex) == NULL){
            printf("%s",a[i]);
            i++;
        }
    }

}  
fclose(file);
return 0;

}

有什么建议?

c linux dev-c++
1个回答
1
投票

您需要将带有CR / LF行结尾的文件'poems.txt'转换为Unix行结尾。这可以使用'tr'命令完成。

tr -d '\r' < input.file > output.file
© www.soinside.com 2019 - 2024. All rights reserved.