Reading a string from file until whitespace c++

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 27K views
nicolegrace
Messages
5
Reaction score
0
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 !
 
Physics news on Phys.org
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:
#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:
#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:
#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: