gpt4 book ai didi

c++ - 从文件中查找最后一个字母为 'a' 的单词

转载 作者:行者123 更新时间:2023-11-30 03:58:23 26 4
gpt4 key购买 nike

ifstream input;
string filename="file.txt";
string word;

input.open(filename.c_str());
int len=word.length();

while(getline(input,word)) {

if(word.at(len-1)='a') {
cout<<word;
}

}

当我执行它时,编译器给出了一个运行时错误,我不明白为什么?我想找到最后一个字符为 'a' 的单词,谢谢

最佳答案

int len=word.length(); 应该在循环中。

目前,len0

你也有错别字 = (assignment) should be == (test for equality)

顺便说一句,从 C++11 开始,您可以使用 word.back()。并且您应该检查该字符串是否为空。

结果:

while (getline(input, word)) {
if (!word.empty() && word.back() == 'a') {
std::cout << word;
}
}

关于c++ - 从文件中查找最后一个字母为 'a' 的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27450684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com