2016-05-14 64 views
-3

所以我有下一個問題,我試圖輸入兩個字符串,其中一個可以爲null其他必須。我試過cin/getline在控制檯中的一行中應用程序

cin>> param1>>param2 

請注意,param1不能爲空參數2可以爲null。 param2爲空時不起作用。

接下來我試着用getline(cin,param1)getline(cin,param2) 這個工程,但我需要在控制檯應用程序的兩行中給params。

我需要從控制檯param1,param2中讀取一行。 請注意,我是這種編程語言的初學者。

感謝

+0

你爲什麼說「所以我有下一個問題」在你的問題,每一個?這與任何問題有什麼關係? –

回答

1

是的,這是不行的,因爲cin然後等待第二個參數。 您需要使用getline()並手動解析字符串。

一種可能性是要做到這一點:

string params, param1, param2; 
getline(cin, params); 
istringstream str(params); 
str >> param1 >> param2; 

注意,參數2將是空的,然後如果只有一個PARAM過去了,因爲stringstream的兩端(CIN並沒有結束)。

話雖這麼說,這仍然不是情況下,像 "parameter 1 with spaces" "parameter 2 with spaces" 工作,因爲istream的簡單分割的空間,不處理引號。

通常,當應用程序需要參數,main()argcargv參數用於從應用程序的命令行讓他們(這裏的報價也適用)

2

cin是閱讀,所以流的方向是相反的:

cin >> param1 >> param2; 
+0

我修改了一下,對不起,我很匆忙 – lolex

1

cinstd::istream的典範。對於任何istream,stream >> x的結果是對istream本身的引用。

istream包含一些標誌來指示先前操作的成功或失敗。

istream也可轉換爲bool。如果之前的操作成功,bool的值將是true,否則(任何原因)該值爲false。

因此,如果我們願意,我們不僅可以鏈接>>操作,還可以鏈接其他檢查。

這可能有點高級,但我認爲你會發現它很有趣。 您可以按原樣編譯並運行該程序。

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


struct success_marker 
{ 
    success_marker(bool& b) 
    : _bool_to_mark(std::addressof(b)) 
    {} 

    void mark(bool value) const { 
     *_bool_to_mark = value; 
    } 
    bool* _bool_to_mark; 
}; 

std::istream& operator>>(std::istream& is, success_marker marker) 
{ 
    marker.mark(bool(is)); 
    return is; 
} 

success_marker mark_success(bool& b) { 
    return success_marker(b); 
} 

void test(const std::string& test_name, std::istream& input) 
{ 
    bool have_a = false, have_b = false; 
    std::string a, b; 

    input >> std::quoted(a) >> mark_success(have_a) >> std::quoted(b) >> mark_success(have_b); 

    std::cout << test_name << std::endl; 
    std::cout << std::string(test_name.length(), '=') << std::endl; 
    std::cout << have_a << " : " << a << std::endl; 
    std::cout << have_b << " : " << b << std::endl; 
    std::cout << std::endl; 
} 

int main() 
{ 
    std::istringstream input("\"we have an a but no b\""); 
    test("just a", input); 

    // reset any error state so the stream can be re-used 
    // for another test 
    input.clear(); 

    // put new data in the stream 
    input.str("\"the cat sat on\" \"the splendid mat\""); 
    // test again 
    test("both a and b", input); 

    return 0; 
} 

預期輸出:

just a 
====== 
1 : we have an a but no b 
0 : 

both a and b 
============ 
1 : the cat sat on 
1 : the splendid mat 
相關問題