【问题标题】:spliting string in C++在 C++ 中拆分字符串
【发布时间】:2021-08-12 05:52:14
【问题描述】:

我想知道如何在整数之前拆分字符串。可能吗? 我编写了一个转换器,它可以从旧的 txt 文件中下载数据,对其进行编辑,然后以新的形式将其保存在新的 txt 文件中。

例如旧文件如下所示:

新行中的每个数据。 转换后的新文件应如下所示:

表示整数之后的所有数据都应该在新的不同行中。

我的代码包含在下面。现在我有一个字符串作为 buf,没有任何白色符号:

我想按照示例中的方式拆分它。

#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;
}

【问题讨论】:

  • 最好在问题中显示源字符串以及您希望将其拆分为文本的内容。
  • 请将您获得的结果显示为文本,并将其与您想要的结果进行比较。 IE。用英语描述它们的不同之处,这有助于阐明目标和问题。它可能会帮助您自己找到算法改进。
  • 对不起,伙计们。我刚刚编辑了帖子
  • 好。继续整合反馈。

标签: c++ string converters txt


【解决方案1】:

您可以尝试使用std::stoi 将当前字符串解析为int;如果成功,您可以在buf 中添加一个换行符。这不会完全拆分字符串,但会在您将其发送到文件时产生您正在寻找的效果,并且可以很容易地适应实际切割字符串并将其发送到向量。

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] + '|';
}

(另外,我相信你已经从其他人那里听说过,但是you shouldn't be using namespace std

【讨论】:

  • 谢谢尼克。我读到使用 namespace std 是一个坏习惯,但我是自学成才的,很难找到好的学习材料
  • StackOverflow 是一个学习良好编码习惯的好地方祝你未来的代码好运!
  • 哈哈,那我会试着看看这里。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多