【问题标题】:How to store a string with multiple whitespaces c++ [duplicate]如何存储具有多个空格的字符串c ++ [重复]
【发布时间】:2018-09-30 07:40:36
【问题描述】:

我的程序应该接受一些输入,例如“你好”。或“我有一个”。 (注意结束点)如果字符串包含“a”则输出“yes”,如果不包含则输出“no”。 问题是 cin 会跳过空格,而 noskipws 似乎不起作用。

我得到的代码:

#include <iostream>
#include <string>
using namespace std;


int main() {
    string sequence;
    cin >> noskipws >> sequence;

    for (auto c : sequence) {
        if (c == 'a') {
            cout << "yes" << "\n";
            return 0;
        }
    }
    cout << "no" << "\n";
}

Input: "where are you."   Output: nothing
Input: "what."            Output: yes

【问题讨论】:

  • 使用std::getline()
  • 这里有没有人解释为什么noskipws在OP的例子中不起作用,为什么std::getline()可以解决它?

标签: c++ string cin


【解决方案1】:

使用 getline() 的解决方案,正如 πάντα ῥεῖ 建议的那样:

#include <iostream>
#include <string>

int main()
{
    std::string sequence;
    std::getline(std::cin, sequence);

    for (auto c : sequence) {
        if (c == 'a') {
            std::cout << "yes\n";
            return 0;
        }
    }
    std::cout << "no\n";
}

【讨论】:

    【解决方案2】:

    你可以使用 std::getline() 或者如果你想逐字选择,你可以试试这个。

    #include <iostream>
    #include <string>
    
    int main(){
        std::string sequence;
        while(std::cin >> sequence){
            for (auto c : sequence) {
                if (c == 'a') {
                    std::cout << "yes\n";
                    return 0;
                }
            }
        }
        cout << "no" << "\n";
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      相关资源
      最近更新 更多