我做了一個函式來計算我從輸入中得到的每一行的所有字符。代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int countAllChars (char inp[])
{
int charCount = 0;
for(int i = 0; inp[i] != '\0'; i ) {
if(inp[i] == '\n' || inp[i] == EOF) {
continue;
} else {
charCount ;
}
}
return charCount;
}
int main ()
{
int total = 0;
char inp[1000];
while(fgets(inp,100,stdin)) {
printf("%d\n", countAllChars(inp));
}
return 0;
}
這按預期作業,例如使用文本檔案input.txt,其中包含:
Password
longpassword
short
aaa
verylongpassword
以及用于運行程式的以下語法:
./binary <input.txt
我的程式列印出來:
8
12
5
3
16
哪個是正確的。我的目標現在是列印出來的字符數的的最短上述檔案的行。使用上面的示例,我知道最短行的字符數為3。我的問題是,我如何獲得這個確切的價值?我考慮將值保存到另一個變數中,然后根據該函式的另一個呼叫檢查該變數,這產生了以下代碼:
int countAllChars (char inp[])
{
int charCount = 0;
for(int i = 0; inp[i] != '\0'; i ) {
if(inp[i] == '\n' || inp[i] == EOF) {
continue;
} else {
charCount ;
}
}
return charCount;
}
int main ()
{
int total = 0;
int shortestLine = 0;
char inp[1000];
while(fgets(inp,100,stdin)) {
shortestLine = countAllChars(inp);
if(shortestLine < countAllChars(inp)) {
shortestLine = countAllChars(inp);
}
}
printf("Shortest line is --> %d\n", shortestLine);
return 0;
}
Not only is the code pretty ugly and obfuscated, but it doesn't work correctly, too. Running the code on the same text file (input.txt with the content above) prints out:
Shortest line is --> 16
Which is obviously not correct.
uj5u.com熱心網友回復:
您在同一行中計算字符兩次,并且總是shortestLine無條件地重新分配:
while(fgets(inp,100,stdin)) {
shortestLine = countAllChars(inp);
if(shortestLine < countAllChars(inp)){
shortestLine = countAllChars(inp);
}
}
初始化一個保存“贏家”的變數并使用另一個變數來跟蹤當前行的長度:
#include <limits.h>
int shortestLine = INT_MAX;
int currentLineLength = INT_MAX;
while(fgets(inp,100,stdin)){
currentLineLength = countAllChars(inp);
if(currentLineLength < shortestLine) {
shortestLine = currentLineLength;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342684.html
上一篇:陣列索引導致越界
下一篇:在特定元素上拆分int陣列
