使用字符串流提取参数

Extracting arguments using stringstream

本文关键字:提取 参数 字符串      更新时间:2023-10-16

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

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 语句中比较指针和整数

正如标题"使用字符串流提取参数"所建议的那样:

我想你正在寻找这个:

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
}
command是一个

字符串,所以command[i]是一个字符。您无法将字符与字符串文本进行比较,但可以将它们与字符文本进行比较,例如

command[i]!=' '

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

您可能需要两个循环,一个外部从字符串流中读取,另一个内部从当前单词中获取字符。要么这样,要么在line中循环字符串(我不建议这样做,因为空格字符比空格多)。或者当然,由于来自字符串流的"输入"已经是空格分隔的,只需打印字符串,无需循环字符。


若要从字符串流中提取所有单词并将其提取到字符串向量中,可以使用以下命令:

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));

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

参考资料: std::istream_iteratorstd::back_inserterstd::copy .