C++if语句比较字符串不起作用
C++ if statement comparing strings not working
我正在开发一个函数,该函数读取文件的行,直到到达文件中的行"XXX",并且计数器跟踪读取了多少行。然后程序计算文件中剩余的行数。我使用if语句来确定何时中断while循环(当行读取等于"XXX"时),并且不满足条件。即使在line=="XXX"时,else语句仍将运行。我的代码出了什么问题?谢谢
#include <string>
#include <iostream>
#include <fstream>
using std::string;
using std::endl;
using std::cout;
using std::ifstream;
int main()
{
//Main function
}
void read_file(string input_file_name)
{
string i_filename = input_file_name;
ifstream infile;
infile.open (i_filename);
string line;
int num_of_terms1 = 0;
int num_of_terms2 = 0;
if (!infile)
{
cout << "Your input file could not be opened."<<endl;
}
else
{
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
if (line == "XXX")
{
break;
}
else
{
cout << line << endl;
num_of_terms1++;
}
}
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
num_of_terms2++;
}
}
cout << "Terms 1: "<<num_of_terms1 <<endl;
cout << "Terms 2: "<< num_of_terms2 <<endl;
infile.close();
}
下面是一个示例输入文件inputfile.txt:
-2 3
4 2
XXX
-2 3
提前感谢您的帮助!
我在www.compileonline.com上测试了这段代码,并重复了您的发现。
在这种环境中,从文件中读取的每个字符串的末尾都有一个字符。
当我将终止行更改为if (line == "XXXr")
时,代码按预期工作。
输入文件的行似乎以"\r\n"结尾,这是windows的标准,但unix文本文件通常以"\n"结尾。
更新:
以下是一个小演示,演示如何删除拖尾回车和换行(或任何其他您想要的内容):
#include <string>
#include <algorithm>
#include <iostream>
void trim_cruft(std::string& buffer)
{
static const char cruft[] = "nr";
buffer.erase(buffer.find_last_not_of(cruft) + 1);
}
void test(std::string s)
{
std::cout << "=== testing ===n";
trim_cruft(s);
std::cout << s << 'n';
}
int main()
{
test(""); // empty string
test("hello worldr"); // should trim the trailing r
test("hellonworldrn"); // don't trim the first newline
}
首先,您应该阅读以下内容:为什么循环条件中的iostream::eof被认为是错误的?
第二条调试线:
cout << line << endl;
在这两种情况下完全相同——您在else语句中,或者您在计算num_of_terms2
,这很令人困惑。更改它们,这样您就可以看到打印的是哪一个。
修复这些问题后,您将看到"else语句将不会继续运行"
正如我在评论中所说,您有两个cout
语句,您应该验证哪一个正在打印XXX
。如果它们都不是,那么问题很可能是字符串中有回车,您可以使用验证其他情况
cout << line << endl; // print is here
if (line == "XXXr")
{
break;
}
else
{
cout << line << endl; // print is here
num_of_terms1++;
}
相关文章:
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- boost::spirit::x3 中的简单字符串解析器不起作用
- 用于拆分空格字符串的程序不起作用
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- 将字符从一个字符串简单分配到另一个字符串不起作用
- C++ 对象数组字符串输入在控制台上不起作用
- 字符串代码不起作用
- 检查字符串中的小写字符或空格.布尔值不起作用
- 在C 中使用Atof将字符串转换为小数不起作用
- 字符串等于不起作用 C++
- 从中间器转换字符串不起作用,出了什么问题?
- 为什么strcpy()不起作用,请接受字符串作为参数
- 在字符串中找到元音不起作用
- C++将字符串写入文本文件中的行;新行问题不起作用
- int 有效,但字符串::size_type不起作用
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- C++字符串不起作用
- 排序功能不起作用(字符串比较问题)