Cout 无法在显示器上打印(控制台)

Cout doesn't print on display (console)

本文关键字:打印 控制台 显示器 Cout      更新时间:2023-10-16

所以我有一个代码应该在某个.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. 文件未成功打开。
  2. 文件已成功打开,但找不到字符串。
  3. 已成功打开文件,并找到字符串。

您有案例 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;
}