【问题标题】:How do i resolve this bug in C++?如何解决 C++ 中的这个错误?
【发布时间】:2021-09-09 05:46:43
【问题描述】:

string 中的vector 接受来自给定string 的输入。

输入:Hello World

预期输出:Hello World

实际输出:你好

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string s1;
    getline(cin, s1);
    vector<string> vs1;
    string s2;
    for (int i = 0; i < s1.size(); i++) {
        if (s1[i] != ' ') {
            s2.push_back(s1[i]);
            continue;
        }
        if (s1[i] == ' ' || i == s1.size() - 1) {
            vs1.push_back(s2);
            s2.clear();
        }
    }
    for (string t : vs1) {
        cout << t << " ";
    }

    return 0;
}

【问题讨论】:

  • 普通输入运算符&gt;&gt; 以空格分隔。您可以将它与例如std::istringstream 将字符串拆分为“单词”。与std::istream_iterator 一起,您只需几行即可填充一个向量:std::getline(std::cin, s1); std::istringstream iss1(s1); std::vector&lt;std::string&gt; vs1(std::istream_iterator&lt;std::string&gt;(iss1), std::istream_iterator&lt;std::string&gt;()); 全部完成,现在vs1 包含输入中的所有“单词”。
  • 至于您当前的代码,是时候学习如何使用调试器在监控变量及其值的同时逐语句执行代码。
  • OT:不要包含&lt;bits/stdc++.h&gt;,这是在一些糟糕的学习材料中教授的讨厌的东西。阅读:stackoverflow.com/Questions/31816095/….

标签: c++ stdvector stdstring


【解决方案1】:

您的第一个if 语句将对除空格之外的任何字符执行。这意味着当i==s1.size()-1 时没有到达第二个if 语句,因为s1[10] == 'd' 用于您的测试输入。

由于您的第一个if 语句包含continue,因此当第一个分支为真时,永远不会评估第二个分支。 continue 语句不应该存在。

【讨论】:

  • 顺便说一下,我不建议你使用这种方法。我支持@Someprogrammerdude 制作的cmets。如果您不熟悉迭代器的概念,他的代码可能会令人困惑,但它们非常有用,绝对值得学习。你绝对应该习惯使用实时调试器。这将使追踪这些类型的错误更加更容易。
【解决方案2】:

你可以使用std::stringstream,这样你就不需要不必要的 if 块了。

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

int main()
{
    std::string s1;
    std::getline(std::cin, s1);
    std::string buffer;                  
    std::stringstream ss(s1);       // Insert the string into a stream

    std::vector<std::string> vs1; // Create vector to hold our words

    while (ss >> buffer)
        vs1.push_back(buffer);

    for (std::string t : vs1) {
        std::cout << t << " ";
    }
    return 0;
}

输出: Hello World

注意:using namespace std; 是不好的做法。 Why is "using namespace std;" considered bad practice?

【讨论】:

    【解决方案3】:

    当您使用 vs1.push_back(s2) 时,您将 s2 添加到其他元素。如果您想为第一个元素添加空间,您甚至不必使用第一个 if。 你在这里:

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main()
    {
    string s1;
    getline(cin,s1);
    vector < string > vs1;
    string s2;
    for(int i=0;i<s1.size();i++)
    {
        s2.push_back(s1[i]);
        
         if(s1[i]==' ' || i==s1.size()-1)
         {
            vs1.push_back(s2);
            s2.clear();
          }
     }
    cout<<vs1[0]<<vs1[1];
    
     return 0;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2014-05-16
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多