Search code examples
c++stringconverterstxt

spliting string in C++


I wonder how to split a string, right before integer. Is it possible? I have written a converter that downloads data from an old txt file, edits it, and saves it in a new form in a new txt file.

For example old file look like:

enter image description here

Every data in new row. New file after convert should look like:

enter image description here

Means that all data after integer should be in a new different line.

My code is included below. Now I have one string as a buf without any white signs:

enter image description here

And I want to split it as shown in the example.

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main () {

    string fileName;

    cout << "Enter the name of the file to open: ";
    cin >> fileName;

    ifstream old_file(fileName + ".txt");
    ofstream new_file("ksiazka_adresowa_nowy_format.txt");

    vector <string> friendsData;
    string buf;
    string data;

    while(getline(old_file, data)) {
        friendsData.push_back(data);
    }
    for(int i=0; i<friendsData.size() ; ++i) {
        buf+=friendsData[i] + '|';
    }
    new_file << buf;

    old_file.close();
    new_file.close();

    return 0;
}

Solution

  • You can try to parse the current string as an int with std::stoi; if it succeeds, you can add a newline to buf. This doesn't exactly split the string, but has the effect you're looking for when you send it to your file, and can be easily adapted to actually cut the string up and send it to a vector.

    for(int i=0; i<friendsData.size() ; ++i) {
        try {
          //check to see if this is a number - if it is, add a newline
          stoi(friendsData[i]);
          buf += "\n";
        } catch (invalid_argument e) { /*it wasn't a number*/ }
        buf+=friendsData[i] + '|';
    }
    

    (Also, I'm sure you've heard this from someone else, but you shouldn't be using namespace std)