C++中fstream读取结果无法与多字符字符串比较问题求助
问题原因及解决办法
问题根源
你的代码仅以空格作为指令分隔符,但NC代码每行开头的G指令前大概率存在换行符(\n)或回车符(\r),这些不可见字符会被读取到字符串w中。控制台输出时,换行符会自动换行,导致你看到的w是正常的G0,但实际w的内容是"\nG0"或"\rG0",因此compare方法返回非0值,无法匹配成功。
此外,逐字符读取的逻辑只处理了空格,没有覆盖制表符等其他空白字符,也会导致分割逻辑不完整。
解决办法
方案1:改进逐字符读取逻辑,处理所有空白字符
引入<cctype>头文件,用isspace()函数识别所有空白字符(空格、换行、回车、制表符等),同时添加对文件末尾无空格结尾的指令的处理:
#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int main() { char c; string w = ""; fstream myfile("your_file_path.xll"); // 替换为实际文件路径 while (myfile.get(c)) { // 识别所有空白字符作为分隔符 if (isspace(static_cast<unsigned char>(c))) { // 跳过空字符串(连续空白字符的情况) if (!w.empty()) { cout << w << "\n"; // 直接用==比较字符串,比compare更直观 if (w == "H") { cout << "header found\n"; } else if (w == "G0") { cout << "rapid travel instruction found\n"; } else if (w == "G1") { cout << "linear interpolation instruction found\n"; } else { cout << "Compare to G0 =" << w.compare("G0") << "\n"; cout << "Compare to G1 =" << w.compare("G1") << "\n"; } cout << "w reseted\n"; w.clear(); } } else { w += c; } } // 处理文件最后一个无空格结尾的指令 if (!w.empty()) { cout << w << "\n"; if (w == "H") { cout << "header found\n"; } else if (w == "G0") { cout << "rapid travel instruction found\n"; } else if (w == "G1") { cout << "linear interpolation instruction found\n"; } } return 0; }
方案2:更优雅的按行读取+分割Token
逐字符读取逻辑繁琐,推荐用getline按行读取文件,再通过stringstream自动分割每行的指令(自动处理所有空白字符):
#include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; int main() { string line; fstream myfile("your_file_path.xll"); while (getline(myfile, line)) { stringstream ss(line); string token; // >> 操作符自动分割所有空白字符 while (ss >> token) { cout << token << "\n"; if (token == "H") { cout << "header found\n"; } else if (token == "G0") { cout << "rapid travel instruction found\n"; } else if (token == "G1") { cout << "linear interpolation instruction found\n"; } else { cout << "Compare to G0 =" << token.compare("G0") << "\n"; cout << "Compare to G1 =" << token.compare("G1") << "\n"; } cout << "token processed\n"; } } return 0; }
验证问题的小技巧
可以在调试时输出字符串的长度,确认是否包含额外字符:
cout << "w content: " << w << ", length: " << w.size() << "\n";
如果G0对应的长度是3而不是2,就说明字符串中包含了换行符或回车符。
内容的提问来源于stack exchange,提问作者lfbaillargeon
相关产品推荐
相关产品推荐

