簡體   English   中英

C++ 使用更多分隔符讀取字符串

[英]C++ reading string using more delimiters

我對 c++ 很陌生。 我的問題是我有一個可以是任意長度並以 \n 結尾的字符串。 例如:

const string s = "Daniel,20;Michael,99\n" (始終是 "name,age;name,age;name,age.......\n")

我想將姓名和年齡分開並將其放入兩個向量中以便可以存儲。 但我不知道如何使用更多分隔符來管理字符串。 所以這個例子會像這樣分開:

向量名稱包含 {Daniel,Michael}

向量年齡包含 {20,99}

您可以為此目的使用stringstreamgetline ,但由於您有一個非常特定的格式,簡單的std::string::find可能會解決您的問題。 這是一個簡單的例子:

#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstddef>

int main() {
    std::string const s = "Daniel,20;Michael,99;Terry,42;Jack,34";

    std::vector<std::string> names;
    std::vector<int> ages;

    std::size_t beg = 0;
    std::size_t end = 0;
    while ((end = s.find(',', end)) != s.npos) {
        names.emplace_back(s, beg, end - beg);
        char* pend;
        ages.push_back(std::strtol(s.c_str() + end + 1, &pend, 10));
        end = beg = pend - s.c_str() + 1;
    }

    for (auto&& n : names) std::puts(n.c_str());

    for (auto&& a : ages) std::printf("%d\n", a);

}

抱歉,我的 C++ 技能已經褪色,但這是我會做的:-

vector <string> names;
vector <string> ages;
string inputString = "Daniel,20;Michael,99;Terry,42;Jack,34";

string word = "";
for(int i = 0; i<inputString.length(); i++)
{
    
    if(inputString[i] == ';')
    {
        ages.push_back(word);
        word = "";
    }
    
    else if (inputString[i] == ',')
    {
        names.push_back(word);
        word = "";
    }
    
    else
    {
        word = word + inputString[i];
    }
}
ages.push_back(word);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM