2013-09-22 39 views
1

提取參數我想輸入一個詞組,並提取短語中的每個字符:使用字符串流

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語句

+2

'lineStream >> commmand' * *已經通過提取空格分開的話。 –

回答

0

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

+0

可以讓用戶輸入insertN andy xu,然後程序首先檢查「insertN」命令,然後它調用另一個函數來檢查對應於該命令的參數。我將如何做到這一點? – Andy

+0

@Andy我會提取所有單詞並放入一個'std :: vector'。然後,向量的索引零始終是命令,您可以將該字符串或整個向量傳遞給您的驗證函數。 –

+0

@Andy看到我的更新答案的方式來做到這一點。 –

3

當你的標題「提取使用字符串流參數」提示:

我認爲你正在尋找這樣的:

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 
}