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

C++ Function to Search for A Numeric Value in a File

我有一个作业,我必须在其中创建一个将文件名作为参数的函数,打开文件,要求用户输入要搜索的值,然后在文件中搜索该值。我被分配用于此任务的文件是一个包含收入和支出值列表的文件。我已经尝试了几乎所有的方法,并且即使我输入了一个我知道在文件中的值,也会继续收到 "value not found" 提示。

密码是

void numberSearch(string fileName)
{
string searchVal;

cout << "\nWhat value would you like to search for?\n";

cin.ignore(); 
getline(cin, searchVal);

ifstream file; //create input file object that will be read from
file.open(fileName);   //"ifstream file (fileName)"

if (!file)
{
    cout << "\nUnable to open file.\n";
    exit(1);
}

string words;

int curLine = 0;  //file line counter

while (getline(file, words))  
{
    ++curLine;  //counts each line in the file

    if (words.find(searchVal) != string::npos) 
    {
        cout << "\nLine " << curLine << " contains " << searchVal << endl;

        file.close();
        return; 
    }

    else
    {
        cout << "\nThe value " << searchVal << " was not found.\n";

        file.close();
        return; 
    }
}
}

非常感谢任何帮助

您需要将 else 部分放在 while 循环之外。否则你的函数将只搜索第一行。

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

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

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