从 C++ 中的文件中获取特定位置的详细信息
grab the detail from particular location from file in c++
char a[133];
char x[4]="ccc";
int line=3,count=1;
//string aa;
//cin>>aa;
ifstream out("text");
while(out.getline(a,4,':')&&(strncmp(a,x,4)))
{cout<<"hi";
cout<<a<<endl;
out.getline(a,4,'n');
}
out.close();
return 0;`
在文本文件中
aaa:1111111
bbb:222222
ccc:333333
ddd:444444
我想跳到特定的行上并抓住细节。 但我没有得到它。 请指导我如何在C ++中做到这一点
毕竟得到了解决方案。您也可以看到结果
在这里
int main(){
ifstream in ("text");
if(!in){cout<<"cannot open"<<endl;}
string buffer;
int line_count=1; size_t line=1;
while(line){
getline(in,buffer);
if(!buffer.find_first_of("bbb:"))
{
cout<<line<<endl;
break;
}
else
{
line=line+1;
}
}
cout<<buffer<<endl;
for(int line_count=0;line_count<line-1&&getline(in,buffer);line_count++)
{
}
getline(in,buffer);
in.close();
return 0;
}
再次感谢
首先,您可以将每一行读入如下std::string
:
std::ifstream in("text");
std::string buffer;
int line_count = 0;
// discard lines until we arrive at the desired line or an error/eof occurs
for(int line_count = 0;
line_cout < line && std::getline(in, buffer);
line_count++) {}
if(in) { // check if last extraction was successful
// process line stored in buffer
}
else {
if(in.eof())
std::cout << "Line-number was invalid" << std::endl;
else
std::cout << "An error occurred" << std::endl;
return -1;
}
您可以在此处找到有关使用iostreams
读取文件的一些详细信息。然后,您可以处理该行。使用成员函数std::string::find_first_of
您可以找到':'
,并使用成员函数std::string::substr
您可以在该位置拆分字符串。
请注意,此方法仅适用于问题中所述的简单格式。对于像"ab:c":"content"
这样的格式,它不会像您期望的那样工作。如果你有这样的格式,你需要编写一个更复杂的解析器,最好使用 Boost.Spirit.Qi
.
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 是与初始类同一内存位置的重新定位类
- 如何在使用网格布局时重叠qwidgets,并将重叠的widget定位在距离窗口边界特定距离的位置
- 我不知道如何定位最高随机数的位置
- 如何在MFC上设置窗口位置以将其定位到屏幕顶部
- 将QGraphicsSvgItem的中心定位在一个位置上。
- 如何定位WinRT异步方法调用中出现错误的位置
- 重定位表项在平面二进制文件中的存储位置