Search code examples
c++stdio

how to ignore quote in fscanf


I have problem with read string from text file. In file there is data in this format:

something="test"

And I want to read string between quotes. So in my program I do:

fscanf(fil,"language=\"%s[^\"]",data);  

or

fscanf(fil,"language=\"%s\"",data);

but I always get test" in variable data. How can I ignore the second quote? Except putting space before in file. I want exactly that format in text file.

I will be grateful for help.


Solution

  • If you don't want to think too deeply about formatting strings you could always read in the full string than take out the sub string that you want.

    Example:

    The following code searches through str for the first " and last " and puts the substring in strNew.

    #include <string>
    #include <iostream>
    
    using namespace std;  //used for ease but not the best to use in actual code.
    
    int main()
    {
      string str = "variable=\"name\"";
      cout << str << endl;
      int first = str.find("\"");
      int last = str.find_last_of("\"");
      string strNew = str.substr (first + 1, last - first -1);
      cout << strNew << endl;
      return 0;
    }