Breaking a single string into multiple strings C++?

后端 未结 3 1090
太阳男子
太阳男子 2020-12-21 21:18

I need to input 3 full names separated by commas

Full Name 1: John, Smith, Flynn
Full Name 2: Walter, Kennedy, Roberts
Full Name 3: Sam, Bass, Clinton

3条回答
  •  [愿得一人]
    2020-12-21 22:11

    void DumpName(char*  pBuffer, char cDelimiter, int iCounter);
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        char full[3][100];
    
        cout << "Enter 3 Full Names :" << endl;
        for (int i=0; i<3; i++) {
             cout << "Full Name " << i+1 << ":" ;
            gets (full[i]);          
        }
    
        for(int i=0; i<3; i++)
        {
            cout << "First Name "<< i+1 << ":" ;
            DumpName(full[i], ',', 0);
        }
    
        for(int i=0; i<3; i++)
        {
            cout << "Middle Name "<< i+1 << ":" ;
            DumpName(full[i], ',', 1);
        }
    
        for(int i=0; i<3; i++)
        {
            cout << "Last Name "<< i+1 << ":" ;
            DumpName(full[i], ',', 2);
        }
    
        return 0;
    }
    
    void DumpName(char*  pBuffer, char cDelimiter, int iCounter)
    {
        int iFound = 0;
    
        char* pStart = pBuffer;
        char* pCurrent = pBuffer;
        while(*pCurrent != '\0')
        {
            if(*pCurrent == cDelimiter)
            {
                if(iFound == iCounter)
                {
                    *pCurrent = '\0';
                    cout << pStart << endl;
                    *pCurrent = cDelimiter;
                    return;
                }
    
                pStart = pCurrent;
                pStart ++;
                iFound ++;
            }
    
            pCurrent ++;
        }
    
        if((iCounter - iFound) == 0)
            cout << pStart << endl;
    }
    

提交回复
热议问题