我想首先说我还在学习,有些人可能认为我的代码看起来很糟糕,但现在就这样了。
所以我有这个文本文件,我们可以调用example.txt。
example.txt中的一行如下所示:
randomstuffhereitem=1234randomstuffhere
我希望我的程序接收item =旁边的数字=我已经使用以下代码开始了一些。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string word;
int main()
{
ifstream readFile("example.txt", ios::app);
ofstream outfile("Found_Words.txt", ios::app);
bool found = false;
long int price;
cout << "Insert a number" << endl;
cout << "number:";
cin >> number;
system("cls");
outfile << "Here I start:";
while( readFile >> word )
{
if(word == "item=")
这是问题所在;首先它只搜索“item =”但是为了找到它,它不能包含在其他字母中。它必须是一个独立的词。
它不会找到:
helloitem=hello
它会找到:
hello item= hello
必须用空格分隔,这也是一个问题。
其次我想找到item =旁边的数字。就像我希望它能够找到item = 1234并且请注意1234可以是任何数字,如6723。
而且我不希望它找到数字之后的内容,所以当数字停止时,它将不再接收数据。喜欢item = 1234hello必须是item = 1234
{
cout <<"The word has been found." << endl;
outfile << word << "/" << number;
//outfile.close();
if(word == "item=")
{
outfile << ",";
}
found = true;
}
}
outfile << "finishes here" ;
outfile.close();
if( found = false){
cout <<"Not found" << endl;
}
system ("pause");
}
答案 0 :(得分:0)
您可以使用以下代码:
bool get_price(std::string s, std::string & rest, int & value)
{
int pos = 0; //To track a position inside a string
do //loop through "item" entries in the string
{
pos = s.find("item", pos); //Get an index in the string where "item" is found
if (pos == s.npos) //No "item" in string
break;
pos += 4; //"item" length
while (pos < s.length() && s[pos] == ' ') ++pos; //Skip spaces between "item" and "="
if (pos < s.length() && s[pos] == '=') //Next char is "="
{
++pos; //Move forward one char, the "="
while (pos < s.length() && s[pos] == ' ') ++pos; //Skip spaces between "=" and digits
const char * value_place = s.c_str() + pos; //The number
if (*value_place < '0' || *value_place > '9') continue; //we have no number after =
value = atoi(value_place); //Convert as much digits to a number as possible
while (pos < s.length() && s[pos] >= '0' && s[pos] <= '9') ++pos; //skip number
rest = s.substr(pos); //Return the remainder of the string
return true; //The string matches
}
} while (1);
return false; //We did not find a match
}
请注意,您还应该更改从文件中读取字符串的方式。你可以读取换行符(std :: getline)或流的末尾,如下所述:stackoverflow question