如何从字符串中提取整数并将它们分配给c ++中的变量?

时间:2016-11-18 05:14:11

标签: c++ string input

我目前正在尝试创建一个带有int源和int目标的对象。 我应该通过从文件中读取一行代码来获取变量。例如:

int source, target;

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

如何从源码中获取0,将目标中的0从我创建的变量中存入?

1 个答案:

答案 0 :(得分:-1)

我已经在你的例子中测试了这个,我希望这有帮助!

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 "";

}

将其实现到项目中时,只需使用stoi(string)将返回的值转换为整数