Pregunta

I want to input a phrase and extract each character of the phrase:

int main()
{
    int i = 0;
    string line, command;
    getline(cin, line); //gets the phrase ex: hi my name is andy
    stringstream lineStream(line);
    lineStream>>command;
    while (command[i]!=" ") //while the character isn't a whitespace
    {
        cout << command[i]; //print out each character
        i++;
    }
}

however i get the error: cant compare between pointer and integer at the while statement

¿Fue útil?

Solución 2

command is a string, so command[i] is a character. You can't compare characters to string literals, but you can compare them to character literals, like

command[i]!=' '

However, you're not going to get a space in your string, as the input operator >> reads space delimited "words". So you have undefined behavior as the loop will continue out of bounds of the string.

You might want two loops, one outer reading from the string stream, and one inner to get the characters from the current word. Either that, or loop over the string in line instead (which I don't recommend as there are more whitespace characters than just space). Or of course, since the "input" from the string stream already is whitespace separated, just print the string, no need to loop over the characters.


To extract all words from the string stream and into an vector of strings, you can use the following:

std::istringstream is(line);
std::vector<std::string> command_and_args;

std::copy(std::istream_iterator<std::string>(is),
          std::istream_iterator<std::string>(),
          std::back_inserter(command_and_args));

After the above code, the vector command_and_args contains all whitespace delimited words from the string stream, with command_and_args[0] being the command.

References: std::istream_iterator, std::back_inserter, std::copy.

Otros consejos

As your title "Extracting arguments using stringstream" suggests:

I think you're looking for this :

getline(cin, line); 
stringstream lineStream(line);

std::vector<std::string> commands; //Can use a vector to store the words

while (lineStream>>command) 
{
    std::cout <<command<<std::endl; 
   //commands.push_back(command); // Push the words in vector for later use
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top