1

我想首先说我还在学习,有些人可能会认为我的代码看起来很糟糕,但它就是这样。

所以我有这个文本文件,我们可以调用 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");
}
4

1 回答 1

0

You can use a code like this:

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
}

Note that you should also change the way you read strings from file. You can either read to newline (std::getline) or to the end of stream, like mentioned here: stackoverflow question

于 2013-03-10T19:22:42.523 回答