[英]How to read a word between “” with ifstream?
包含以下內容的ini文件:address =“ localhost” username =“ root” password =“ yourpassword” database =“ yourdatabasename”
並且我需要使用ifstream在兩個“”之間找到單詞,並將其放入char中。
有沒有辦法做到這一點??
如果每對之間有換行符,則可以執行以下操作。
std::string line; //string holding the result
char charString[256]; // C-string
while(getline(fs,line)){ //while there are lines, loop, fs is your ifstream
for(int i =0; i< line.length(); i++) {
if(line[i] != '"') continue; //seach until the first " is found
int index = 0;
for(int j= i+1; line[j] != '"'; j++) {
charString[index++] = line[j];
}
charString[index] = '\0'; //c-string, must be null terminated
//do something with the result
std::cout << "Result : " << charString << std::endl;
break; // exit the for loop, next string
}
}
我將按以下方式處理:
std::istream& operator>>( std::istream &, NameValuePair & );
然后,您可以執行以下操作:
ifstream inifile( fileName );
NameValuePair myPair;
while( ifstream >> myPair )
{
myConfigMap.insert( myPair.asStdPair() );
}
如果您的ini文件包含節,每個節都包含“命名-值”對,那么您需要讀到節末,這樣您的邏輯就不會使用流故障,而會對狀態機使用某種抽象工廠。 (您讀了一些東西然后確定是什么,從而確定了您的狀態)。
至於實現將流讀入您的名稱/值對,可以使用getline(使用引號作為終止符)來完成。
std::istream& operator>>( std::istream& is, NameValuePair & nvPair )
{
std::string line;
if( std::getline( is, line, '\"' ) )
{
// we have token up to first quote. Strip off the = at the end plus any whitespace before it
std::string name = parseKey( line );
if( std::getline( is, line, '\"' ) ) // read to the next quote.
{
// no need to parse line it will already be value unless you allow escape sequences
nvPair.name = name;
nvPair.value = line;
}
}
return is;
}
請注意,在完全解析令牌之前,我沒有寫入nvPair.name。 如果流式傳輸失敗,我們不想部分寫入。
如果任一getline失敗,流將保持失敗狀態。 這將在文件結束時自然發生。 如果由於該原因而導致異常失敗,我們不希望引發異常,因為這是處理文件末尾的錯誤方法。 如果它在名稱和值之間失敗,或者名稱沒有尾隨=符號(但不為空),則可能會拋出該錯誤,因為這不是自然現象。
請注意,這允許在引號之間使用空格甚至換行符。 它們之間的任何內容都將被讀取,而不是另一個引號。 您將必須使用轉義序列來允許它們(並解析值)。
如果您使用\\“作為轉義序列,那么當您獲得該值時,如果它以\\結尾(以及將其更改為引號),則必須“循環”,並將它們連接在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.