line.find 不会编译,line 不会声明

line.find won't compile, line is not declared

本文关键字:line 声明 编译 find      更新时间:2023-10-16

我是一个非常新手的程序员,我正试图理解字符串的查找函数。在大学里,我们被告知要使用c字串,这就是为什么我认为它不起作用。问题来了,当我编译,有一个编译错误,line没有声明。这是我的代码:

 #include <iostream>
 #include <fstream>
 #include <cstring>
 #include <string>
 using namespace std;
int main()
{
    char test[256];
    char ID[256];

    cout << "nenter ID: ";
    cin.getline(ID, 256);
    int index = line.find(ID);
    cout << index << endl;
    return 0;
}

请帮助,它已经变得非常令人沮丧,因为我需要理解这个函数来完成我的任务:/

您正在尝试使用c风格字符串。但是find是c++ string类的成员。如果您想使用C风格的字符串,请使用操作C风格字符串的函数,如strcmp, strchr, strstr等。

假设您实际上也在test中输入了一些数据,那么这样做的一种方法是:

char *found = strstr(test, ID);
if ( !found )
    cout << "The ID was not found.n";
else
    cout << "The index was " << (found - test) << 'n';

因为发现函数是成员函数string类,所以应该声明string类的对象。我认为你应该这样做:

string test = "This is test string";
string::size_type position;
position = test.find(ID);
if (position != test.npos){
    cout << "Found: " << position << endl;
}
else{
    cout << "not found ID << endl;
}