C++ Cout不';t在显示器上打印(控制台)
所以我有一个代码,它应该在某个.txt文件中找到一个字符串,如果输入在文件中,它会说“是的,我找到了”,但如果不是,它应该说“没有找到任何东西”,但它只是跳过这一步并结束。 我是初学者,对于任何明显的错误,我深表歉意C++ Cout不';t在显示器上打印(控制台),c++,cout,C++,Cout,所以我有一个代码,它应该在某个.txt文件中找到一个字符串,如果输入在文件中,它会说“是的,我找到了”,但如果不是,它应该说“没有找到任何东西”,但它只是跳过这一步并结束。 我是初学者,对于任何明显的错误,我深表歉意 #include <stdio.h> #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std
#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
cin.get();
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
#包括
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
内部主(空)
{
setlocale(LC_ALL,“”);
弦赫莱达特;
整数偏移量;
弦线;
ifstreammyfile;
cout.flush();
库赫莱达;
如果(Myfile.is_open())
{
而(!Myfile.eof())
{
getline(Myfile,line);
if((offset=line.find(hledat,0))!=string::npos)
{
cout.flush();
cout有三种可能的情况
文件未成功打开
文件已成功打开,但未找到字符串
已成功打开文件,并找到字符串
您有案例1和案例3的打印输出,但没有案例2
顺便说一句,您的循环条件是错误的。请使用对getline调用的结果,即读取尝试后的ostream对象本身
while (getline(MyFile, line))
{
...
}
如果读取尝试失败,循环将终止,这将发生在您读取最后一行之后。按照您的方式,您将尝试在最后一行之后读取,这将不成功,但您仍将尝试处理该不存在的行,因为在循环重新开始之前,您不会检查eof。只需注释掉//cin.get();
,您不需要它
输出:
Welcome, insert the string to find in the file.
apple
Found it ! your input was : apple
除此之外,它就像一个符咒
更正代码:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
//cin.get(); <----- corrected code
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
内部主(空)
{
setlocale(LC_ALL,“”);
弦赫莱达特;
整数偏移量;
弦线;
ifstreammyfile;
cout.flush();
无法通过if/else
块跟踪所有路径,并找出哪个路径给出了您看到的结果。输入文件的内容是什么?您让它搜索的字符串是什么?给定准确的输入,您希望得到什么准确的输出?我很好奇。谁教您在(!file.eof())时使用
?乍一看,你有一个cin.get和cin>>hledat,所以基本上你需要输入两次…也许这就是问题所在?我认为变量偏移量的类型错误,应该是size\u t或类似的。太棒了,谢谢分享!假设我输入了文件中没有的内容(只有一列名称,如“John,Rick”等等…如果我输入George,它会跳过“对不起,找不到任何东西”部分