Reading string from file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • areddy
    New Member
    • Mar 2007
    • 1

    Reading string from file

    Program in C++ on Linux.
    I want to extract the strings string1 and string2 from the line:
    config.?.getstr ing=("string1,s tring2");

    This line is in another file. There are 100 other lines like this in the file that start with config but only "getstring" is unique. My program should not be aware of what string1 and string2 nor how many strings there are.

    My program should pick up string1, sring2 etc and assign variables to them.

    My code so far:
    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    using std::string;
    
        int main()
        {
          string tmp = "getstring";
          string tmp1;
          fstream file_op("/path/of/file",ios::in);
    	if (!file_op)
    	  {	   
    	    cout << "cant open file\n";
    	    return 1;
    	  }
    
    	    while (! file_op.eof())
    	      {
    		getline(file_op,tmp1);
    
    		 cout << tmp1 << endl;
    		
                                     //string tmp2; not working says return type should be char! 
    		// tmp2 = strstr (tmp1, tmp);
    		// cout << tmp2 << endl; 
    	   // string sub = theline.substr(18);
    	   // string tokens = strtok(sub," ,)(;");
    	   // cout << sub << "\n";	      
    	      }
            file_op.close();
    
            return 0;
        }
    Right now the program just opens the file and reads through it ...is there a way of specifing which line to get throught the getline function? Like saying the line contains "getstring" so pull out that line?
    I am struggling with the strstr function. Also i dont know how i am supposed to find out the number of strings in that line and assign variables to them.

    Please assist

    Thank you
    Last edited by sicarie; Mar 30 '07, 01:20 AM. Reason: Please use [code] and [/code] tags around your code.
  • DhananjayNangare
    New Member
    • Mar 2007
    • 8

    #2
    May be you can use fseek() like below
    /* fseek example */
    Code:
    #include <stdio.h>
    
    int main ()
    {
      FILE * pFile;
      pFile = fopen ( "myfile.txt" , "w" );
      fputs ( "This is an apple." , pFile );
      fseek ( pFile , 9 , SEEK_SET );
      fputs ( " sam" , pFile );
      fclose ( pFile );
      return 0;
    }
    Last edited by Ganon11; Mar 30 '07, 11:44 AM. Reason: code tags added

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      The above code is written in C, but you should be able to get it working if you change the include statement to

      Code:
      #include <cstdio>

      Comment

      Working...