串联数组元素c++的子串

substr concatenating array elements c++

本文关键字:子串 c++ 数组元素      更新时间:2023-10-16

我正在构建一个函数,从数组中提取姓氏并将名称打印到屏幕上。我已经能够提取数组中的第一个姓氏,但输出将第一个索引的名字与以下索引位置的姓氏连接起来。下面是我的代码,谢谢你的帮助!

{
    stringstream ss; 
    string name;

    for(int i=0; i < elements; i++)
    {
        ss << first[i];
        ss >> name;
        int pos = name.find(",");
        cout << pos;
        string last = name.substr(0,pos);
        cout << """ << last << """ << endl;

    }
    cout << endl;
}

这是因为您使用字符串流的方式。

每次从数组中读取新名称时,都会将其添加到输出缓冲区中。然后从缓冲区中读取下一个单词,因此,您永远不会跳过第一个名字。对于你正在做的事情,你可以把字符串流全部消除,只使用标准的输入和输出(cin/cout)。否则,每次读取新字符串时都要清除缓冲区(ss.clear());

    for(int i = 0; i < elements.size(); i++){
        int pos = elements[i].find(",");
        cout << """ << elements[i].substr(0,pos) << """ << endl;
    }

尝试以下代码:

int main()
{
   string name = "asd,kkaa";
   int pos = name.find(",");
   if(string::npos != pos)
   {
      string part1 = name.substr(0,pos);
      string part2 = name.substr(pos+1);
      cout << """ << part1 << """ << endl;
      cout << """ << part2 << """ << endl;
   }
   return 0;
}
// output:
// "asd" 
// "kkaa"

我觉得可以,所以可以给我们更多你的输入值吗?