簡體   English   中英

在C ++中按空間分隔用戶輸入的更好解決方案是什么?

[英]What's better solution to separate user input by space in C++?

我正在閱讀C ++ Primer並進行其練習。 它要我獲取用戶的輸入並以空格' '分隔。 所以我想出2解決方案。

第一個解決方案:

vector<string> vector1;
string input;
string temp = ""; // temperary hold each word value in input.

string x1 = "";
char x2 = 'b';

x1 += x2;

cout << x1 << endl;

getline(cin, input);

input += " ";

for (string::size_type index = 0; index != input.size(); index++)
{
    if (!isspace(input[index]))
    {
        temp += input[index];
    }
    else
    {
        if (temp.size() > 0)
        {
            vector1.push_back(temp);
            temp = "";
        }
    }
}

第二解決方案

vector<string> vector1;
string input;
string temp = ""; // temperary hold each word value in input.

string x1 = "";
char x2 = 'b';

x1 += x2;

cout << x1 << endl;

getline(cin, input);

//input += " ";

for (string::size_type index = 0; index != input.size(); index++)
{
    if (!isspace(input[index]))
    {
        temp += input[index];
    }
    else
    {
        if (temp.size() > 0)
        {
            vector1.push_back(temp);
            temp = "";
        }
    }
}

if (!temp.empty())
{
    vector1.push_back(temp);
}

它們之間的區別是,第一個解決方案是為用戶輸入添加空間,而第二個解決方案則是檢查是否不添加最后一個單詞。 我想知道哪個是更好的解決方案?

如果有更好的解決方案,請告訴我。

我會這樣寫:

std::vector<std::string> data;

std::copy(std::istream_iterator< std::string>(std::cin), 
          std::istream_iterator< std::string>(),
          std::back_inserter(data));

它與@ K-ballo的答案幾乎相同,除了我讓std::copy直接從輸入流(即std::cin )而不是從std::stringstream讀取。

演示: http//www.ideone.com/f0Gtc

-

或者您可以使用vector的構造函數,完全避免std::copy

 std::vector<std::string> data(std::istream_iterator<std::string>(std::cin), 
                               std::istream_iterator<std::string>());

大功告成! 演示: http : //www.ideone.com/Szfes

如果發現難以閱讀,請改用以下方法:

 std::istream_iterator<std::string> begin(std::cin), end;
 std::vector<std::string> data(begin, end);

演示: http : //www.ideone.com/PDcud

在C ++中,讀取以空格分隔的值非常容易,並且已內置在該語言中。 我可能是錯的,但看起來您過於復雜了。

std::string line;
if (std::getline(std::cin, line)) {
    std::stringstream ss(line);
    std::vector<std::string> inputs_on_this_line(
              std::istream_iterator<std::string>(ss)
            , std::istream_iterator<std::string>()    );
    //do stuff with the strings on this line.
}

您可以輕松地將輸入從流中拆分為字符串分隔的值,然后使用以下命令將它們插入向量中:

string input;

... get the input, perhaps with getline(cin, input); ...

stringstream input_stream( input );
vector<string> vector1;

std::copy(
    (std::istream_iterator< std::string >( input_stream )), std::istream_iterator< std::string >()
  , std::back_inserter( vector1 )
);

std::istream_iterator< std::string >對將通過一次提取std::string (在讀取字符串直到找到空格字符之前)來對input_stream進行迭代。 std::back_inserter將為每個字符串調用push_back進入vector

暫無
暫無

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

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