2013-03-10 35 views
1

我想先说我还在学习,有些人可能会认为我的代码看起来很糟糕,但是在这里。在它之后找到Word + X字母

所以我有这个文本文件,我们可以调用example.txt。

example.txt文件中的一个行可以是这样的:

randomstuffhereitem=1234randomstuffhere 

我想我的程序采取旁边,是该项目的数量=我已经使用下面的代码启动一下就可以了。

这是问题;首先它只搜索“item =”但找到它,它不能与其他字母一起使用。它必须是一个独立的词。

它不会找到:

helloitem=hello 

它会发现:

hello item= hello 

它用空格分开,这也是一个问题。

其次,我想找到item =旁边的数字。就像我希望它能够找到item = 1234并且请注意1234可以是任何数字,如6723.

而且我不希望它找到数字后面的内容,所以当数字停止时,它不会在任何数据。像项目= 1234hello必须是项目= 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

您可以使用这样的代码:

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

+0

问题是我不知道代码是干什么的。我不知道99%是什么。我的代码更简单,也许不太好......可能很糟糕......但它很容易理解。我也不知道在哪里插入你的代码。 – Thomja 2013-03-10 19:53:50

+0

所以我做了这个代码(不知道,如果这是你的想法,但是...) 编辑:我不能粘贴代码在这里...我去哪里粘贴代码?我不想回答我自己的问题... – Thomja 2013-03-10 19:57:12

+0

如果你打算学习编程,你需要尝试理解我发布的代码。我使用每行注释对其进行了注释以简化它。 您可以将此代码作为单独的函数粘贴(即在'int main()'之上)。然后你称它为'get_price(word,remaining,number)'。 你的代码没有解决任务,所以你需要改变它。我已经向您展示了如何改变它的示例。 我不认为您可以在评论中发布代码,但您可以编辑问题或将代码上传到pastebin.com并发布链接。 – Aneri 2013-03-10 22:09:02

相关问题