-1

I'm currently trying to create an object that takes an int source and an int target. I'm supposed to get those to variables from reading a line of code from a file. For example:

int source, target;

string fileline="<edge id="0" source="0" target="1" />"

How do I get that 0 from source and that one from target into the variables I created to store them in?

  • You can use cstyle sscanf. https://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm – MayurK Nov 18 '16 at 05:16
  • 1
    For this kind of input, an xml parser may help: http://stackoverflow.com/questions/170686/what-is-the-best-open-xml-parser-for-c – dvnguyen Nov 18 '16 at 05:21

1 Answers1

-1

I've tested this on your example, I hope this helps!

using namespace std;

/*
When trying to get the 0 after the "id=" in:
 "<edge id="0" source="0" target="1" />"

subString="id="
surrChar (surrounding character)='\"'
fullString="<edge id="0" source="0" target="1" />"
return="0"

Function will return an empty string if subString was not in fullString
*/
string getValueFromString(string subString, char surrChar, string fullString) {

 int subStringLength = subString.length();
 int fullStringLength = fullString.length();

 /*
 minus three because after the substring,
 there will have to be two surrounding characters around your value
 and at least one character that is your value
 */
 int indexToCheckTo = fullStringLength - subStringLength - 3;

 for(int index = 0; index <= indexToCheckTo; ++index) {

  // sub string in fullString
  string ssInFullString = "";

  // get a substring in the fullString to check if it is
  // the same as subString
  for(int subIndex = index; subIndex < index + subStringLength; ++subIndex) {

   ssInFullString += fullString[subIndex];

  }

  // if the substring just obtained is the same as the original substring,
  // and the character after this subString is the surrChar
  if( !ssInFullString.compare(subString)
   && fullString[index + subStringLength] == surrChar) {

   string retString = "";

   // start at the index after the surrChar
   // go until either you hit the end of the string
    // or the current char is surrchar
   for( int subIndex = index + subStringLength + 1;
    subIndex < fullStringLength && fullString[subIndex] != surrChar;
    ++subIndex) {

    retString += fullString[subIndex];

   }

   return retString;

  }

 }

 return "";

}

When implementing this into a project, just use stoi(string) to convert the returned value into an integer

ibstevieb123
  • 96
  • 10