Skip to content

Posts from the ‘C and C++ Examples’ Category

18
Jul

Split a String Into Words Using a Vector of Strings and Iterate through it in C++

Next c++ example shows how to split a string into words by namespaces (or end of line character), store it into a vector of strings and then iterate throug it (mai.cpp).

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main(int argc, const char * argv[]) {
 
    string str1("the brown fox jumped over the lazy dog");
    vector<string> vector1;
    istringstream iss(str1);
 
    while (iss) {
        string word;
        iss >> word;
        //cout << word << endl;
        vector1.push_back(word);
    }
 
    for (int i; i < vector1.size(); i++) {
        cout << vector1[i] << endl;
    }
 
    return 0;
}
18
Jul

Create a Vector of Strings and Iterate Through it in C++

In the next example we will create a vector of strings and will iterate through it (main.cpp).

#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
int main(int argc, const char * argv[]) {
 
    string str1[] = {"the", "brown", "fox", "jumped", "over", "the", "lazy", "dog"};
    vector<string> vector1(str1, end(str1));
 
    for (int i; i < vector1.size(); i++) {
        cout << vector1[i] << endl;
    }
    return 0;
}
18
Jul

Split a C++ String Into Words by Spaces or End of Lines

Next example shows you how to split a string into multiple words delimited by spaces or end of line (main.cpp).

#include <iostream>
#include <string>
#include <sstream>
 
using namespace std;
 
int main(int argc, const char * argv[]) {
 
    string str1("the brown fox jumped over the lazy dog");
    istringstream iss(str1);
 
    while (iss) {
        string word;
        iss >> word;
        cout << word << endl;
    }
    return 0;
}
17
Jul

C++ Example: A Class to Read a File

Here is a C++ example of a class to read content of a text file and store it in a buffer (char *). Everything is done in class’s constructor.

The header file (ReadFromFile.h):

#include <iostream>
#include <fstream>
 
using namespace std;
 
class ReadFromFile {
private:
    string fileName;
    long long buffLength;
    char *buff;
 
public:
    ReadFromFile(string file);
    ~ReadFromFile();
 
    char* displayBuffer();
    long long getFileLength();
};
</fstream></iostream>

Read more »