C语言CSV文件搜索程序故障求助:输入存在城市始终返回ERROR
Hey there! No worries about your English at all—let’s work through why your program keeps returning "ERROR" no matter which existing city you search for. Here are the most common pitfalls and fixes to check:
Incorrect String Comparison
This is the #1 mistake for C beginners! You can’t use==to compare strings in C—this checks if the pointers are the same, not the actual text. You need to use thestrcmp()function from<string.h>instead. For example:// Wrong if (csv_city == input_city) { ... } // Correct if (strcmp(csv_city, input_city) == 0) { ... } // Returns 0 when strings matchDon’t forget to add
#include <string.h>at the top of your code.Unwanted Whitespace/Newlines
When reading lines from the CSV withfgets()or reading user input, the resulting string often includes a trailing\n(newline) or\r(carriage return). These invisible characters will break your string comparison. Fix this by trimming them off:// Remove \n and \r from the end of a string char *line = ...; line[strcspn(line, "\n\r")] = '\0';Also, check if your CSV has extra spaces around city names (like
" New York "instead of"New York") or if the user is entering spaces accidentally. You can add a trim function to strip leading/trailing whitespace from both input and CSV values.File Opening/Reading Failures
Make sure your program is actually opening the CSV file successfully. Always check if the file pointer isNULLafterfopen()—if it is, your program might be reading garbage data (or nothing at all):FILE *fp = fopen("your_file.csv", "r"); if (fp == NULL) { printf("ERROR: Could not open file\n"); return 1; }Double-check the file path too—if the CSV isn’t in the same directory as your executable, you need to use the full path (like
"C:/projects/cities.csv"on Windows or"/home/user/cities.csv"on Linux).CSV Field Parsing Errors
If you’re usingstrtok()or another method to split CSV lines into fields, make sure you’re grabbing the correct column for the city name. For example, if your CSV is structured asCity,Population,Zip, you need to take the first token, not the second or third.
Also, note thatstrtok()modifies the original string, so if you need to keep the full line, make a copy first.Case Sensitivity
Your program might be case-sensitive—so"London"won’t match"london"or"LONDON". To fix this, convert both the input city and the CSV city to the same case (all lowercase or all uppercase) before comparing:// Convert a string to lowercase void to_lower(char *str) { for (int i = 0; str[i]; i++) { str[i] = tolower((unsigned char)str[i]); } }
If none of these fix the issue, sharing a snippet of your code (especially the parts where you read the CSV, handle input, and do the comparison) would help pinpoint the exact problem.
内容的提问来源于stack exchange,提问作者Jessijow Black

