Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Reading a string from file until whitespace c++

  1. Sep 10, 2011 #1
    I am newbie to programming , I am trying to write a program in c++ to read strings from the file until white space [ space/ newline] each time i encounter white space i append to the string read append a symbol "$" and push to the buffer. and for the same string append another symbol "(" and push this again to buffer.

    example :

    say I have file as following :example.txt

    cat dog monkey
    tree daimond

    So it should read as following in the buffer

    Buf[] = cat$cat(dog$dog(monkey$monkey(tree$tree(daimond$daimond(


    can someone help me c++ code for this . thank you !
     
  2. jcsd
  3. Sep 10, 2011 #2
    You can use an object of type std::ifstream to read from the text file. If you use the operator ">>" to read from the file, where the std::ifstream is to the left of the ">>" and an std::string is to the right, you can read strings in a manner like you described.

    Code (Text):
    #include <fstream>
    #include <string>
    using namespace std;

    int main()
    {
        string s;
        ifstream file("example.txt");
        file >> s;
        return 0;
    }
    For this program, s would contain "cat" if example.txt was like you described.

    You can have this done in a loop to read from the file multiple times.

    You can check the [boolean] value of the ifstream itself to see if there is more to read.
    Here is a way to read the entire file:

    Code (Text):

    #include <fstream>
    #include <string>
    using namespace std;

    int main()
    {
        string s;
        ifstream file("example.txt");
        while(file >> s)
        {
            //do stuff
        }
        return 0;
    }

     
    You can use an object of type std::stringstream to write to a buffer.

    Code (Text):

    #include <sstream>
    #include <iostream>
    using namespace std;

    int main()
    {
        stringstream ss;
        string s;
        ss << "testing ";
        ss << '$';
        ss << 12345;

        s = ss.str();
        cout << s << endl;

        return 0;
    }
     
    For this program, the console would show
    testing $12345

    ss is effectively a buffer, but I showed how you can copy its contents into the std::string s, since an std::string may be more like the buffers with which you may be familiar.
     
    Last edited: Sep 10, 2011
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook