OP的fgets()
用途不明確,portNum[sizeof(line)] = (char)line;
肯定是錯誤的。
相反:如何讓下面的getchar()
代碼更fgets()
樣:
// assumed missing code
#define N 100
int c;
char portNum[N];
size_t num = 0;
// size and EOF detection added (which should have been there)
while(num + 1 < sizeof portnum && (c = getchar()) != '\n' && c != EOF) {
portNum[num++] = c;
}
portNum[num] = '\0';
// assumed missing code
if (c == EOF && num == 0) Handle_EndOfFile_or_InputError();
else ...
這可以fgets()
代碼
#define N 100
char portNum[N+1]; // 1 larger for the \n
if (fgets(portNum, sizeof portNum, stdin)) {
// lop off potential trailing \n
portNum[strcspn(portNum, "\n")] = '\0';
...
} else {
Handle_EndOfFile_or_InputError();
}
被替換爲'與fgets(行的sizeof(線),標準輸入)'第二個參數是要複製到str中的最大字符數(包括終止空字符)。給它定義一個值。另外,'fgets'將繼續讀取,直到遇到換行符。不需要while循環。 – Ayush
'portNum [sizeof(line)] =(char)line;'你有什麼想法你在做什麼? –