0

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;
}
Jackdaw
  • 7,626
  • 5
  • 15
  • 33

1 Answers1

0

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)

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • Thank you Nick. I read that using namespace std is a bad habit but I am self-taught and its realy hard to find good materials to learn – Bartosz Jurkiewicz May 23 '21 at 19:53
  • StackOverflow is unironically a pretty good place to learn good coding habits, if only because we tend to be very bold about pointing out bad ones :P In all seriousness, good on you for getting yourself to this point and good luck with your future code! – Nick Reed May 23 '21 at 19:59
  • 1
    Haha, I'll try to look here some time then. Thank you again! – Bartosz Jurkiewicz May 23 '21 at 20:10