C++ 在C++;如果文件中的一行包含特定字符
我已经从一个文本文件中读取了这些行,我想检查该行是否包含$符号 这就是我目前得到的:C++ 在C++;如果文件中的一行包含特定字符,c++,filestream,C++,Filestream,我已经从一个文本文件中读取了这些行,我想检查该行是否包含$符号 这就是我目前得到的: int main() { ifstream data_store; string line; data_store.open("c:\\test.txt"); while (!data_store.eof()) { getline(data_store, line); if (line.find("$")) cout
int main() {
ifstream data_store;
string line;
data_store.open("c:\\test.txt");
while (!data_store.eof())
{
getline(data_store, line);
if (line.find("$"))
cout << "1: " << line << endl;
}
data_store.close();
system("PAUSE");
return 0;
}
intmain(){
ifstream数据存储;
弦线;
数据存储打开(“c:\\test.txt”);
而(!data_store.eof())
{
getline(数据存储,行);
if(第行查找($))
cout要检查一行是否包含使用的内容,需要检查find
返回的值,以确保它是有效的返回值。为此,我们将它与find()进行比较
如果找不到任何内容,将返回。这就是它将每一行作为std::string::npos查找的原因。当作为bool
进行计算时,仍然认为它是正确的。因此重构代码时,您将:
while (getline(data_store, line))
{
if (line.find("$") != std::string::npos)
cout << "1: " << line << endl;
}
while(getline(数据存储,行))
{
if(line.find(“$”)=std::string::npos)
cout这是一件小事,但@NathanOliver解决方案的一个变体是使用for
循环:
ifstream data_store("c:\\test.txt");
for ( string line; getline(data_store, line); ) {
if ( line.find("$") != string::npos )
cout << "1: " << line << endl;
}
// ...
ifstream数据存储(“c:\\test.txt”);
for(字符串行;getline(数据存储,行);){
if(line.find($)=string::npos)
我昨天做了,但忘了更新
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool contains_number(const string &c);
int main()
{
int count = 0;
{
string line1[100];
ifstream myfile("D:/Users/Jarvan/Desktop/test.txt");
int a = 0;
if (!myfile)
{
cout << "Error opening output file" << endl;
system("pause");
return -1;
}
while (!myfile.eof())
{
getline(myfile, line1[a], '\n');
if (contains_number(line1[a]))
{
count += 1;
cout << line1[a] << "\n";
}
else cout << "\n";
}
}
cout << count <<endl;
system("pause");
return 0;
}
bool contains_number(const string &c)
{
return (c.find_first_of("$") != string::npos);
}
#包括
#包括
#包括
使用名称空间std;
bool包含_编号(常量字符串和c);
int main()
{
整数计数=0;
{
字符串行1[100];
ifstream myfile(“D:/Users/Jarvan/Desktop/test.txt”);
int a=0;
如果(!myfile)
{
CUT是否有一个发现部分的问题?还有问题吗?或者你只是问如何输出到一个文件?我不工作C++,我不知道它是否比较整个字符串“$”或搜索它在LIN。-哈?你有虫子,但这根本不是真的。