用于在文件中搜索数值的C ++函数

时间:2016-09-27 03:13:06

标签: c++ function file search filestream

我有一个分配,我必须创建一个函数,该函数将文件名作为参数,打开文件,要求用户输入要搜索的值,然后在文件中搜索该值。我用于此作业的文件是一个包含收入和费用值列表的文件。我已经尝试过几乎所有的东西并继续收到未找到的值#34;即使我输入我知道的值在文件中,也会提示。

代码是

rake prepare_ios

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

您需要将else部分放在while循环的一边。否则,您的功能只会搜索第一行。

答案 1 :(得分:0)

我很无聊所以我决定也这样做。即使它已经解决了,我也会发布我的帖子。 (赞成解决问题的乐趣;))

using namespace std;

int testfile(string filename, int &line, int &character)
{
    ifstream is(filename, std::ios::in);
    if (!is.is_open()) return 1; //1 = no file

    cout << "Search for what value?" << endl;
    string value;
    cin >> value;

    string buf;

    while (getline(is,buf))
    {
        ++line;
        if (buf.find(value) != buf.npos)
            {
                character=buf.find(value); //the part that got lost in edit
                return 0; //value found, returning 0
            }
    }

    return 2; //return 2 since no value was found
}

在main()下调用:

main()
{

    int line=0; //what line it is
    int character=0; //what character on that line

    int result=testfile("test.txt", line, character); //debug+passing as reference

    if (result == 1)cout << "could not find file" << endl;
    if (result == 2)cout << "could not find value" << endl;

    if (result == 0)
        cout << "found at line# " << line << " character# " << character << endl;

    return 0;
}

通过引用传递值可以让我们在原始范围内使用它们。因此,该函数既可以为调试提供错误,也可以为我们的范围目的提供有用的结果。

关闭fstream是没有必要的,因为让范围将为我们处理:see here

呵呵,几乎就像在学校一样;)