0

I am having problems with my code for this homework assignment. Everything is outputting correctly except I am getting an extra space after my "first" output. My code is shown below please help me to fix the extra space.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {

    string userStr; 
    bool inputDone = false; 
    while(!inputDone)
    {
        bool commaCheck = false;    
        do
        {   
            
            cout << "Enter input string:" << endl;
            getline(cin, userStr);
            if (userStr == "q")     
            {
                inputDone = true;
                break;
            }
            else{
                
            for (unsigned int i = 0; i < userStr.length(); i++)
            {
                if (userStr[i] == ',')  
                    commaCheck = true;
            }
            if (!commaCheck)    
            {
                cout << "Error: No comma in string." << endl << endl;
            }
        }
        } while (!commaCheck);
    if(!inputDone)
    {
        string first, second;
        istringstream stream(userStr);
        getline(stream, first, ',');
        stream >> second;

        cout << "First word: " << first << endl;
        cout << "Second word: " << second << endl;
        cout << endl;
    }
    }
    return 0;
}
  • 2
    i known this is not code review time, but consider using `userStr.find(',') != string::npos` to check for the presence of a comma – Thomas Nov 03 '21 at 19:00
  • 1
    What is your input and what is the output? – n314159 Nov 03 '21 at 19:02
  • Do you mean a blank line or a single space? – jwezorek Nov 03 '21 at 19:03
  • 1
    When you commingle extraction (`operator>>`) with `getline`, you need to be aware of what state those leave the stream in. – Eljay Nov 03 '21 at 19:20
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Nov 04 '21 at 13:04

1 Answers1

0

If you use std::getline(stream, first, ','); and there is a space between your word and the comma then it will be of course in first. Because you told std::getline: Get me everything until you see a comma.

If somebody inputs " a ,b", then you have leading and trailing spaces in first.

You need to "trim" your string, meaning remove leading and trailing spaces.

There are many trim functions published here on SO. Please see for example here

If you see an additional problem, then please inform

A M
  • 14,694
  • 5
  • 19
  • 44