我想输入一个短语并提取该短语的每个字符:

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++;
    }
}

但是我得到了错误:无法在while语句之间比较指针和整数

最佳答案

command是字符串,因此command[i]是字符。您不能将字符与字符串文字进行比较,但是可以将它们与字符文字进行比较,例如

command[i]!=' '

但是,您不会在字符串中得到空格,因为输入运算符>>会读取以空格分隔的“单词”。因此您具有未定义的行为,因为循环将继续超出字符串的范围。

您可能需要两个循环,一个从字符串流中读取外部内容,一个内部从当前单词中获取字符。要么,要么循环遍历line中的字符串(我不建议这样做,因为除了空格以外,还有更多的空白字符)。或者,当然,由于字符串流中的“输入”已经用空格分隔,因此只需打印字符串即可,而无需遍历字符。

要将所有单词从字符串流中提取到字符串 vector 中,可以使用以下命令:
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));

在上面的代码之后, vector command_and_args包含来自字符串流的所有空格分隔的单词,其中command_and_args[0]是命令。

引用: std::istream_iterator std::back_inserter std::copy

关于c++ - 使用stringstream提取参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18947404/

10-11 03:46
查看更多