簡體   English   中英

反轉C中字符串數組中的項目

[英]Reverse items in an array of strings in C

我需要有關我的代碼的幫助。 我已經完成了一個代碼(如下)來從 .txt 文件中讀取數字。 前兩個數字將放在一個 int 變量中,從第二行開始的數字將放在一個字符串數組中。 但是現在,我想反轉字符串數組並放入一個新的字符串數組。 我一直在嘗試解決這個問題,但我無法解決。

前任。 文件:

 3 8
 10000001
 11101001
 00100101
 11000010

我需要:listOfNumbersReversed = {"11000010","00100101","11101001","10000001"}

代碼:

int main() {
FILE *file = fopen("file.txt", "r");
if (file == NULL) {
    fprintf(stderr, "Cannot open file.txt: %s\n", strerror(errno));
    return 1;
}
// read the 2 numbers
int primNum, secNum;
if (fscanf(file, "%d %d\n", &primNum, &secNum) != 2) {
    fprintf(stderr, "invalid file format\n");
    fclose(file);
    return 1;
}
// count the number of items that can be read
char line[100];
int counter;
for (counter = 0; fscanf(file, "%99s", line) == 1; counter++)
     continue;

printf("Total number of items: %d\n", counter);

// Rewind and re-read the contents into the array
rewind(file);
char listOfNumbers[counter][100];
int i;
if (fscanf(file, "%d %d\n", &primNum, &secNum) != 2) {
    fprintf(stderr, "cannot reread the numbers\n");
    fclose(file);
    return 1;
}
for (i = 0; i < counter; i++) {
    if (fscanf(file, "%99s", listOfNumbers[i]) != 1) {
        // Cannot read all the numbers file changed ?
        printf("could only read %d numbers out of %d\n", i, counter);
        counter = i;
        break;
    }
}

// Testing Results
printf("1st Number: %d\n", primNum);
printf("2nd Number: %d\n\n", secNum);
printf("List of Numbers on Array:\n");
for (i = 0; i < counter; i++) {
    printf("%s\n", listOfNumbers[i]);
}
fclose(file);

//Reversing the array of strings
char listOfNumbersReversed[counter][secNum];
for(i = counter - 1; i>=0; i--){
    int j = 0;
    memcpy(&listOfNumbersReversed[j], &listOfNumbers[i], secNum);
    j++;
}

//Testing Results
printf("\n\nList of Numbers Reversed on Array:\n");
for (i = 0; i < counter; i++) {
    printf("%s\n", listOfNumbersReversed[i]);
}

return 0;
}

ps:secNum變量是數組中itens的大小

你真的很親密,但這里有幾件事。

  1. 將 j 變量移到循環外,這樣每次循環時它都不會重置為零。
  2. 在數組中添加空間以存儲 '\0' 字符串終止。
  3. 將要復制的字符數加 1
    char listOfNumbersReversed[counter][secNum+1];
    int j = 0;
    for (i = counter - 1; i >= 0; i--)
    {
      memcpy (&listOfNumbersReversed[j][0], &listOfNumbers[i][0], secNum+1);
      j++;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM