C++ 如何阅读“之间的单词”&引用;用ifstream?

C++ 如何阅读“之间的单词”&引用;用ifstream?,c++,ifstream,C++,Ifstream,包含以下内容的ini文件: address=“localhost” username=“root” password=“您的密码” database=“yourdatabasename” 我需要用ifstream找到两个“”之间的单词,并将其放入一个字符中 有没有办法做到这一点???如果每对夫妇之间都有换行符,您可以执行以下操作 std::string line; //string holding the result char charString[256]; // C-string whi

包含以下内容的ini文件: address=“localhost” username=“root” password=“您的密码” database=“yourdatabasename”

我需要用ifstream找到两个“”之间的单词,并将其放入一个字符中


有没有办法做到这一点???

如果每对夫妇之间都有换行符,您可以执行以下操作

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::字符串行//保存结果的字符串
字符字符串[256];//C字串
while(getline(fs,line)){//当有行时,loop,fs是您的ifstream
对于(int i=0;istd::cout我将按如下方式进行处理:

  • 创建一个表示名称-值对的类
  • 使用
    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失败,则流将处于失败状态。这将在文件末尾自然发生。如果由于该原因失败,我们不希望引发异常,因为这是处理文件结尾的错误方法。如果名称和值之间失败,或者名称没有尾随的=号,则可以引发异常(但不是空的),因为这不是自然现象

请注意,这允许引号之间使用空格甚至换行符。引号之间的任何内容都将被读取,而不是另一个引号。您必须使用转义序列来允许这些内容(并解析值)


如果您使用\“作为转义序列,那么当您获得值时,如果它以\结尾,则必须“循环”(以及将其更改为引号),并将它们连接在一起。

每对key=value之间是否有换行符?是的,它们之间有换行符。我想你的意思是
char*
,而不是
char
。除非这是为了满足接口要求,否则使用
std::string
.Thx几乎肯定会更好,但我不知道如何编程。你能帮忙吗?