【问题标题】:How to split string by my own delimiter如何用我自己的分隔符分割字符串
【发布时间】:2026-01-11 13:35:02
【问题描述】:

程序应将输入的数字字符串和数字分隔符作为输入,并在单独的行中输出 4 个单词。

例子

Please enter a digit infused string to explode: You7only7live7once
Please enter the digit delimiter: 7
The 1st word is: You
The 2nd word is: only
The 3rd word is: live
The 4th word is: once

提示:getline() 和 istringstream 会有所帮助。

我无法找到正确使用 getline() 的方法/位置。

下面是我的程序。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string userInfo;
cout << "Please enter a digit infused string to explode:" << endl;
cin >> userInfo;
istringstream inSS(userInfo);
string userOne;
string userTwo;
string userThree;
string userFour;
inSS >> userOne;
inSS >> userTwo;
inSS >> userThree;
inSS >> userFour;
cout << "Please enter the digit delimiter:" << endl;
int userDel;
cin >> userDel;
cout <<"The 1st word is: " << userOne << endl;
cout << "The 2nd word is: " << userTwo << endl;
cout << "The 3rd word is: " << userThree << endl;
cout << "The 4th word is: " << userFour <<endl;

return 0;
}

我目前的输出是这样的

Please enter a digit infused string to explode:
Please enter the digit delimiter:
The 1st word is: You7Only7Live7Once
The 2nd word is: 
The 3rd word is: 
The 4th word is: 

【问题讨论】:

  • 输出 userDel 并告诉我它说了什么。 :)
  • 你不会以任何方式使用你的userDel,这是意料之中的
  • 那么您是否想知道在哪里使用您甚至可能不需要的特定功能,而不是实际执行所需的任务?为什么?
  • userDel = 7 我还没有输出它,因为我必须找到一种方法来检测它并绕过它来输出单词。

标签: c++ string extract getline istringstream


【解决方案1】:

这就是您一直在寻找的。请注意,getline 可以采用可选的第三个参数char delim,您可以告诉它在此处停止读取,而不是在行尾。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
    string userInfo, userOne, userTwo, userThree, userFour;
    char userDel;

    cout << "Please enter a digit infused string to explode:" << endl;
    cin >> userInfo;
    istringstream inSS(userInfo);

    cout << "Please enter the digit delimiter:" << endl;
    cin >> userDel;

    getline(inSS, userOne, userDel);
    getline(inSS, userTwo, userDel);
    getline(inSS, userThree, userDel);
    getline(inSS, userFour, userDel);

    cout <<"The 1st word is: " << userOne << endl;
    cout << "The 2nd word is: " << userTwo << endl;
    cout << "The 3rd word is: " << userThree << endl;
    cout << "The 4th word is: " << userFour <<endl;

    return 0;
}

【讨论】:

    【解决方案2】:

    cin &gt;&gt; userInfo; 将消耗所有内容,直到一个空格。

    getline(cin, userInfo); 将消耗直到换行符为止的所有内容。

    我猜你的情况并没有什么不同。

    【讨论】:

    • 是的,但是如果你利用getline的第三个参数呢?