2016-11-18 3 views
-1

В настоящее время я пытаюсь создать объект, который принимает int int и int target. Я должен заставить эти переменные читать строку кода из файла. Например:Как извлечь целые числа из строки и назначить их переменным в C++?

int source, target; 

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

Как я могу получить, что 0 из источника, и что один из мишени в переменных, которые я создал, чтобы хранить их в?

+0

Вы можете использовать cstyle sscanf. https://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm – MayurK

+1

Для такого ввода парсер XML может помочь: http://stackoverflow.com/questions/170686/what-is-the-best-open- XML-парсер-для-с – dvnguyen

ответ

-1

Я тестировал это на вашем примере, надеюсь, это поможет!

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

 
}

При реализации этого в проект, просто использовать Стой (строка), чтобы преобразовать возвращаемое значение в целое число

Смежные вопросы