Cout 无法在显示器上打印(控制台)
Cout doesn't print on display (console)
所以我有一个代码应该在某个.txt文件中找到一串字符,如果输入在文件中,它说"是的,我找到了它",但当它不是时,它应该说"没有找到任何东西",但它只是跳过该步骤并结束。我是初学者,对于任何明显的错误,我深表歉意。
#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;
}
有三种可能的情况。
- 文件未成功打开。
- 文件已成功打开,但找不到字符串。
- 已成功打开文件,并找到字符串。
您有案例 1 和 3 的打印输出,但没有案例 2。
顺便说一下,你的循环条件是错误的。 使用 getline 调用的结果,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;
}
相关文章:
- c ++控制台应用程序,如何在控制台外部打印字符
- 控制台打印时间功能产生1
- 如何通过按 F2 或 F3 等键使控制台打印某些内容
- cout 不打印任何内容到控制台
- 如何在 C++ 中将 U32 字符串和 U16string 打印到控制台
- 打印到文件和控制台 C++
- 在 c++ 中打印到控制台的最佳方式是什么?
- 我的控制台正在打印随机单词以及没有执行正确的数学运算
- C++控制台打印在同一行上,带回车符
- 硬编码字符串与强制转换为 PUCHAR 并打印到控制台时从控制台读取的字符串的结果不同
- V8 控制台.log不打印
- 使用 C++ shell 为 C++ 中的 2 D 动态数组赋值,控制台不会打印出任何内容
- cURL 保持打印传输到控制台?
- SDL 未打印到控制台
- qDebug() 在升级到 ubuntu 17.10(和 Fedora)后停止工作(不再打印到控制台)
- 使用具有 UTF8 编码的源文件将 UTF8 符号打印到 Windows 控制台
- 如何在 ATL COM 模块中打印控制台输出
- 打印到控制台或字符串/流
- Cout 无法在显示器上打印(控制台)
- 禁止从导入的 DLL 打印控制台