我在檔案中有以下資料:
Name
Surname
#include <stdio.h>
#define FILENAME "file.txt"
#define MAXSIZE 128
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
FILE *file = fopen(FILENAME, "r");
if (!file) {
perror(FILENAME);
return 1;
}
int ch;
size_t i = 0;
char array[3][MAXSIZE];
for(int a=0; a < 3; a )
{
while (i < MAXSIZE - 1 && ((ch = getc(file)) != EOF))
{
if (ch == '\n')
break;
array[a][i ] = ch;
}
/* null-terminate the array to create a string */
array[a][i] = '\0';
}
fclose(file);
for(int a=0; a < 3; a )
{
for(int i=0; i < 10; i )
{
printf("%c", array[a][i]);
}
}
}
當我運行這個程式時,它會給我這樣的輸出
“
如何修改它,使其不會輸出垃圾?這是我之前帖子的鏈接: 鏈接
uj5u.com熱心網友回復:
正如我在評論中指出的:
您的列印回圈
for (int i=0; i < 10; i ) { printf("%c", array[a][i]); }需要在array[a][i] == '\0'——if (array[a][i] == '\0') break;在printf().您還需要
i在 while 回圈之前(但在for回圈之后)重置為 0。如果您i在第一個 for 回圈中宣告,則不會遇到您遇到的問題。
請注意,您呼叫了兩個不同的變數i(一個size_t i = 0;在回圈之前;另一個for (int i = 0; …)在列印時),一個隱藏另一個。這可能會導致混亂。
這些更改可能會導致以下代碼:
#include <stdio.h>
#define FILENAME "file.txt"
#define MAXSIZE 128
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
FILE *file = fopen(FILENAME, "r");
if (!file) {
perror(FILENAME);
return 1;
}
char array[3][MAXSIZE];
for (int a = 0; a < 3; a )
{
int ch;
size_t i = 0;
while (i < MAXSIZE - 1 && ((ch = getc(file)) != EOF))
{
if (ch == '\n')
break;
array[a][i ] = ch;
}
array[a][i] = '\0';
}
fclose(file);
for (int a = 0; a < 3; a )
{
for (int i = 0; i < 10; i )
{
if (array[a][i] == '\0')
break;
printf("%c", array[a][i]);
}
}
}
也沒有明顯的理由不使用以下方法列印資料:
for (int a = 0; a < 3; a )
puts(array[a]);
或者
for (int a = 0; a < 3; a )
printf("%s\n", array[a]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529130.html
標籤:数组C
上一篇:將字串正確拆分為陣列陣列
下一篇:將字串正確拆分為陣列陣列
