簡體   English   中英

C ++ istream-如何使用空格讀取字符串

[英]C++ istream - how to read string with whitespace

在下面的小程序中,我想用空格讀取inputString:

#include <string>
#include <sstream>
#include <iostream>


int main( int argc , char ** argv ) {
   std::string inputString(" ITEM ");
   std::istringstream inputStream( inputString );

   //Template:

   T value;

   inputStream.unsetf(std::ios::skipws);
   inputStream >> value;

   std::cout << "Value: [" << value << "]" << std::endl;
   std::cout << "StringPos: " << inputStream.tellg() << std::endl;
   std::cout << "State: " << inputStream.good() << std::endl;
}

產生輸出:

Value: []
StringPos: -1
State: 0

如果刪除unsetf()調用,則會得到:

Value: [ITEM]
StringPos: 4
State: 1

即如預期的那樣當空白被忽略時。 所以-很明顯,“不要跳過空白”設置有誤。 有小費嗎?

編輯:添加類似模板的“ T值”后,該示例不再編譯。 但重要的是

inputStream >> value;

作品。 以下元代碼也應該工作:

if is_string(T)
   value = inputString;   // String values are assigned directly
else 
   inputStream >> value;  // Other types.

喬金 -

采用:

std::string line;
if(std::getline(inputStream, line)) {
    // line contains one line from the input stream
} else {
    // inputStream is empty, EOF or in error state
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM