[英]User input string handling
我有一個簡單的C函數,我有一個用戶提供一個路徑名,該函數檢查它是否是有效的文件。
# include <stdio.h>
# include <string.h>
int main(void) {
char cFileChoice[256];
FILE * rInputFile;
unsigned int cFileLength;
printf("\nPlease supply a valid file path to read...\n");
fgets(cFileChoice, 255, stdin);
cFileLength = strlen(cFileChoice) - 1;
if (cFileChoice[cFileLength] == "\n") {
cFileChoice[cFileLength] = "\0";
}
rInputFile = fopen(cFileChoice, "r");
if (rInputFile != NULL) {
printf("Enter 'c' to count consonants or enter 'v' for vowels: ");
}
else {
printf("Not a valid file\n");
}
return 0;
}
只有在運行此文件后,無論文件是否為有效路徑,該文件都將返回為無效。 我刪除了newline
\\n
並將其替換為null terminator
\\0
但是,它仍然無法識別正確的路徑。
我對C的經驗非常少,我不知道我應該在哪里糾正這個問題?
編輯:
這些是我收到的編譯警告:
test.c: In function ‘main’:
test.c:15:34: warning: comparison between pointer and integer [enabled by default]
if (cFileChoice[cFileLength] == "\n") {
^
test.c:16:34: warning: assignment makes integer from pointer without a cast [enabled by default]
cFileChoice[cFileLength] = "\0";
^
我再也不確定如何糾正這些“警告”?
"\\n"
和"\\0"
是字符串文字( "\\0"
是一個特別奇怪的字符串文字,在那)。 您想要與字符文字進行比較: '\\n'
和'\\0'
。
你還需要一個=
你想在第二個比較中得到==
(應該與'\\0'
比較的那個)。
您應該閱讀comp.lang.c
FAQ部分8, 字符和字符串 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.