string.compare for c++
我要求用户输入一个单词,然后让我的程序将其与输入 .txt 文件进行比较 但即使我在 data.txt 中准确输入一个单词,它仍然执行 false。
//------------in my data.txt---------
// Banana Bed Today
// Apples Chair Window
// Corn Tomorrow Hive
string testData;
cout<<"enter Data: ";
cin>>testData;
for(i=0; i<s.size()-1; i++){
if (testData.compare(s[i]->name) == 0)
cout<<"Right\n";
if (youkno.compare(s[i]->name) != 0)
cout<<"Wrong\n";
}
如果我提示 Banana 那么输出执行错误
I am asking user to input a word then have my program compare it with an input .txt file
but even tho I type in exactly a word in data.txt it still executes false.
//------------in my data.txt---------
// Banana Bed Today
// Apples Chair Window
// Corn Tomorrow Hive
string testData;
cout<<"enter Data: ";
cin>>testData;
for(i=0; i<s.size()-1; i++){
if (testData.compare(s[i]->name) == 0)
cout<<"Right\n";
if (youkno.compare(s[i]->name) != 0)
cout<<"Wrong\n";
}
if i prompt Banana then output excuted wrong
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将: 替换
为:,
您可能会发现它变得非常明显。您的一根弦很可能并不完全符合您的预期。
If you replace:
with:
you may find it becomes blindingly obvious. There's a good chance that one of your strings is not quite what you expect.
s[i]->name
里有什么?如果您从文件中读取该数据,则可能已将行结尾包含在name
变量中。另外,为什么不使用
operator==
?编辑:刚刚注意到你有一个错误。你的 for 循环应该是
否则你不会比较
s
中的最后一个值项What is in
s[i]->name
? If you read that data from a file, you may have included the line endings in thename
variable.Also, why not use
operator==
?EDIT: just noticed you have an off by one error. your for loop should be
Otherwise you don't compare the last value item in
s