line.find 不会编译,line 不会声明
line.find won't compile, line is not declared
我是一个非常新手的程序员,我正试图理解字符串的查找函数。在大学里,我们被告知要使用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;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- line.find 不会编译,line 不会声明