该程序从名为" input.txt"的文件中获取输入。但它没有输出正确的外观和说顺序。该程序应输入21和114421.输出应为1211和21241211,但它只是给我无意义的数字。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char input[1024]; //The input element
char result[1024]; //The next element
int length = 0; //The length of the input
int resultLength = 0; //The length of the result
FILE *openFile;
openFile = fopen("input.txt", "r");
do{
fgets(input, 1024, openFile);
} while((input[length++] != '.') && (!feof(openFile)));
length -= 1; //Decrement length because of the length++ that just executed
//Go through the loop, adding to the result each time the chain stops
fclose(openFile);
char prev = input[0]; //The previous character
int count = 1; //The count in the current chain
int i, j = 0;
for(i=1; i < length; i++){
if(input[i] == prev){
count++; //If the chain is unbroken, increment the count
} else{
//If the chain breaks, store the count and digit in result and reset count
result[j++] = count + '0';
result[j++] = prev;
count = 1;
}
//Set prev to be the current digit
prev = input[i];
}
//Handle the last digit using the current value of count and prev
result[j++] = count + '0';
result[j++] = prev;
//Print out the result
printf("The next element in the sequence is: ");
resultLength = j;
for(i=0; i < resultLength; i++){
printf("%c", result[i]);
}
printf("\n");
system("pause");
return 0;
}
答案 0 :(得分:0)
像这样修复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char input[1024];
char result[2*sizeof(input)];
int length = 0;// The length of the input
FILE *openFile = fopen("input.txt", "r");
if(!openFile){
perror("fopen:");
exit(EXIT_FAILURE);
}
while(fgets(input, 1024, openFile)){
char *p = strchr(input, '\n');
if(!p){
fprintf(stderr, "Input too long!\n");
exit(EXIT_FAILURE);
}
*p = 0;//chomp newline
length = p - input;
if(*input == '.' && !input[1]){
puts("c u!");
return 0;
}
//conversion
int resultLength = 0;
int i, j;
for(i = 0; i < length; i = j){
int count = 1;
for(j = i + 1; input[i] == input[j]; ++j)
++count;//Count of repeated characters
while(count > 9){//Processing when the count exceeds 9 E.g 111111111111 ==> 9131
result[resultLength++] = '9';
result[resultLength++] = input[i];
count -= 9;
}
result[resultLength++] = count + '0';
result[resultLength++] = input[i];
}
result[resultLength] = 0;//Add NUL charancter to last for %s of printf
//Print out the result
printf("The next element in the sequence is: %s\n", result);
}
fclose(openFile);
return 0;
}