-1
我目前正在嘗試創建一個對象,它需要一個int源和一個int目標。 我應該從文件中讀取一行代碼來獲取這些變量。例如:如何從字符串中提取整數並將它們分配給C++中的變量?
int source, target;
string fileline="<edge id="0" source="0" target="1" />"
如何獲取0從源代碼和一個從目標到我創建將它們存儲在變量?
我目前正在嘗試創建一個對象,它需要一個int源和一個int目標。 我應該從文件中讀取一行代碼來獲取這些變量。例如:如何從字符串中提取整數並將它們分配給C++中的變量?
int source, target;
string fileline="<edge id="0" source="0" target="1" />"
如何獲取0從源代碼和一個從目標到我創建將它們存儲在變量?
我已經測試過你的例子,我希望這有助於!
using namespace std;
/*
When trying to get the 0 after the "id=" in:
\t "<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) {
\t int subStringLength = subString.length();
\t int fullStringLength = fullString.length();
\t /*
\t minus three because after the substring,
\t there will have to be two surrounding characters around your value
\t and at least one character that is your value
\t */
\t int indexToCheckTo = fullStringLength - subStringLength - 3;
\t for(int index = 0; index <= indexToCheckTo; ++index) {
\t \t // sub string in fullString
\t \t string ssInFullString = "";
\t \t // get a substring in the fullString to check if it is
\t \t // the same as subString
\t \t for(int subIndex = index; subIndex < index + subStringLength; ++subIndex) {
\t \t \t ssInFullString += fullString[subIndex];
\t \t }
\t \t // if the substring just obtained is the same as the original substring,
\t \t // and the character after this subString is the surrChar
\t \t if(\t !ssInFullString.compare(subString)
\t \t \t && fullString[index + subStringLength] == surrChar) {
\t \t \t string retString = "";
\t \t \t // start at the index after the surrChar
\t \t \t // go until either you hit the end of the string
\t \t \t \t // or the current char is surrchar
\t \t \t for(\t int subIndex = index + subStringLength + 1;
\t \t \t \t subIndex < fullStringLength && fullString[subIndex] != surrChar;
\t \t \t \t ++subIndex) {
\t \t \t \t retString += fullString[subIndex];
\t \t \t }
\t \t \t return retString;
\t \t }
\t }
\t return "";
}
當實現成一個項目這一點,只需使用Stoi旅館(字符串)返回的值轉換爲整數
可以使用cstyle sscanf的。 https://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm – MayurK
對於這種輸入,xml解析器可能有所幫助:http://stackoverflow.com/questions/170686/what-is-the-best-open- XML解析器換-C – dvnguyen